Monthly Archives: July 2018

The Node.js Update - #Week 30 - 27 July, 2018

By Ferenc Hamori

The Node.js Update - #Week 30 - 27 July, 2018

Below you can find RisingStack‘s collection of the most important Node.js news, updates & tutorials from this week:

Google Chrome Labs introduces ndb

ndb is an improved debugging experience for Node.js, enabled by Chrome DevTools.

ndb has some powerful features exclusively for Node.js:

  • Child processes are detected and attached to.
  • You can place breakpoints before the modules are required.
  • You can edit your files within the UI. On Ctrl-S/Cmd-S, DevTools will save the changes to disk.
  • By default, ndb blackboxes all scripts outside current working directory to improve focus. This includes node internal libraries (like _stream_wrap.js, async_hooks.js, fs.js) This behaviour may be changed by “Blackbox anything outside working dir” setting.

In addition, you can use all the DevTools functionality that you’ve used in typical Node debugging:

  • breakpoint debugging, async stacks (AKA long stack traces), async stepping, etc…
  • console (top-level await, object inspection, advanced filtering)
  • eager evaluation in console (requires Node >= 10)
  • JS sampling profiler
  • memory profiler

LinkedIn is offering 6 totally FREE courses covering Node.js development

To celebrate Node Summit, Linkedin unlocked six courses covering Node.js. Watch them all, completely free, between now and Monday, August 20.

The Node.js Update - #Week 30 - 27 July, 2018

Node.js development courses from LinkedIn Learning cover Node.js development concepts and best practices.

Deploying a Stateful Node.js Application on Google Cloud Kubernetes Engine [Longform Tutorial]

In this article, we’ll guide you through the process of deploying a stateful, Dockerized Node.js app on Google Cloud Kubernetes Engine! As an example application, we will use Ghost – the open-source blogging platform we use to run the RisingStack blog and serve ~150K readers/month.

Takeaway: Once you go through this tutorial you’ll be able to follow these processes & ideas to deploy any stateful application on Kubernetes!

You Can Now Write Google Cloud Functions with Node.js 8

Let’s take a look at how to use the Node.js 8 environment by deploying a function that uses a couple of features that weren’t available in Node.js 6. The specific version of Node.js 8 that Google is currently using is 8.11.1.

The Node.js Update - #Week 30 - 27 July, 2018

Probably the most significant change between Node.js 6 and 8 is the introduction of support for the async and await keywords. Node.js 8 also adds other useful items such as object spread syntax.

Supercharge your debugging experience with Node Inspector & ndb

Node Inspector lets you to use the DevTools user interface with the native Node debugger. DevTools can now connect directly to the Node process!

The Node.js Update - #Week 30 - 27 July, 2018

Using the chrome debugger is very much the same like using the debugger for client side code. You set breakpoints, execute the code, step over the breakpoints and find the bug.

We’re not done yet. On 20 July Google Chrome labs team open sourced their advanced debugging tool — ndb!

npm install -g ndb

It’s like any other npm package, very simple to use and install.

The Node.js Update - #Week 30 - 27 July, 2018

We now have a new chrome instance for the sole purpose of debugging. Epic!

Developing Real-Time Web Applications with Server-Sent Events

TL;DR: Server-Sent Events (SSE) is a standard that enables Web servers to push data in real time to clients. In this article, we will learn how to use this standard by building a flight timetable demo application with React and Node.js. However, the concepts you will learn following this tutorial are applicable to any programming language and technology.

The Node.js Update - #Week 30 - 27 July, 2018

In order to learn how to use Server-Sent Events, we are going to develop a simple flight timetable application (similar to those flight trackers you can find at any airport). The timetable app will consist of a simple web page showing a list of flights as shown in picture.

[EVENT] Designing Microservice Architectures with Node.js & Kubernetes

During the course of these two days, we will cover a high-level architectural overview of what is needed to design, develop and maintain an application built with microservices.

We will examine a microservices application developed adhering to current best practices, deploy it on Kubernetes and add the necessary infrastructural elements to make it resilient and self-healing.

Previous Node.js Updates:

From the previous Weekly Node.js Update:

  • Node.js 10.7.0 (Current) Released
  • Operationalizing Node.js for Server Side Rendering at Airbnb
  • N-API available in LTS release

& more…

We help you to stay up-to-date with Node.js on a daily basis too. Check out Node.js Daily!

Source:: risingstack.com

The Node.js Update - #Week 29 - 13 July, 2018

By Tamas Kadlecsik

The Node.js Update - #Week 29 - 13 July, 2018

Below you can find RisingStack‘s collection of the most important Node.js news, updates & tutorials from this week:

Node.js 10.7.0 (Current) is out – update now!

  • console: The console.timeLog() method has been implemented.
  • deps:
    • Upgrade to libuv 1.22.0.
    • Upgrade to ICU 62.1 (Unicode 11, CLDR 33.1).
  • http: Added support for passing both timeout and agent options to http.request.
  • inspector: Expose the original console API in require('inspector').console.
  • napi: Added experimental support for functions dealing with bigint numbers.
  • process:
    • The process.hrtime.bigint() method has been implemented.
    • Added the --title command line argument to set the process title on startup.
  • trace_events: Added process_name metadata.
  • Added new collaborators: codebytere – Shelley Vohr

Download the latest Node.js version now!

Operationalizing Node.js for Server Side Rendering at Airbnb

As Airbnb builds more of its Frontend around Server Side Rendering, and they took a look at how to optimize server configurations to support it.

The Node.js Update - #Week 29 - 13 July, 2018

Server side rendering represents a different workload from the canonical, mostly I/O workload that Node.js excels at. Understanding the cause of anomalous behavior allowed us to address it with off the shelf components with which we had existing operational experience.

N-API: Next generation APIs for Node.js native addons available across all LTS release lines

You may have heard that Node.js has experimental support for N-API, a new API for native modules. Not anymore! N-API is now a stable and fully supported feature of Node.js as of version 10. It is also available as an experimental feature in Node.js 8 and 6.

The Node.js Update - #Week 29 - 13 July, 2018

With N-API, native module developers can compile their module once per platform and architecture, and make it available for any version of Node.js that implements N-API. This holds true even for versions of Node.js that are built with a different VM, e.g. Node-ChakraCore.

npm enables two-factor authentication protection for packages

You can now beta-test two-factor authentication protection for individual packages in the npm Registry. This setting requires that every publication of a protected package be authorized by a one-time password. This requirement is enforced even if maintainers of that package haven’t required two-factor auth for publication themselves—they’ll still be prompted for a code for this package. If a maintainer hasn’t enabled two-factor auth at all, they’ll be unable to publish the package until they do.

The Node.js Update - #Week 29 - 13 July, 2018

You can test this feature using the npm canary client, npmc. It’s recommended to invoke the canary using npx: npx npmc. You can also install the canary build of npm directly by running npm install -g npmc@latest.

[EVENT] Designing Microservice Architectures with Node.js & Kubernetes

During the course of these two days, we will cover a high-level architectural overview of what is needed to design, develop and maintain an application built with microservices.

We will examine a microservices application developed adhering to current best practices, deploy it on Kubernetes and add the necessary infrastructural elements to make it resilient and self-healing.

[EVENT] Today is the last day to get early-bird tickets for JS Interactive!

Today is the last day to get early bird tickets for #JSInteractive. Save $349 USD by registering NOW: http://bit.ly/JSIEarlybird

The event takes place in Vancouver, Canada from October 10-12!

Previous Node.js Updates:

From the previous Weekly Node.js Update:

  • Postmortem for Malicious ESlint Packages Published on npm
  • Testing Node.js in 2018
  • Node.js REPL in Depth

& more…

We help you to stay up-to-date with Node.js on a daily basis too. Check out Node.js Daily!

Source:: risingstack.com

Why 'This' in JavaScript

By William Imoh

While JavaScript is a fun and powerful language, it can be tricky and requires a proper understanding of its underlying principles to mitigate common errors.

In this post, we shall be introducing you to the this keyword, its behaviour and the hard choices behind it. These will be detailed using appropriate examples to better drive home the point.

What is this?

Developers make the mistake of thinking that this refers to the “scope” of the function within which it’s encountered. This isn’t true because whenever a function is invoked, it runs in a new execution context until its execution is completed. Each execution context usually references an object and the value of that object translates to the value of this.

For us to properly understand what this is, we would first need to go over two important concepts:

  • Context
  • Call-Site

Context

Commonly in the English language, once a noun is defined in a sentence, subsequent references to the subject noun will be done using a pronoun. Understand?

First Statement: Brad is a good boy.
Second Statement: He is a very brilliant boy!

Who is a brilliant boy? Brad… obviously!

This is quite the same in JavaScript, the first statement creates the context, while this functions like ‘he’ in the second statement and is used to reference the subject in the first statement.

this refers to the context of an executing function.

This would mean that during every function execution, the focus is on the new execution context which is redetermined whenever a function is invoked, and since the context holds a reference to an object, the value of this is updated accordingly.

It is impractical to assume that the value of this is fixed and always refers to the function’s scope, the value of this is, in fact, dynamic and determined by how a function is called and where it is called:

Different sections in a JavaScript program run in an execution context and maintain that context until there is a switch to a new context. The context of an executing function references the object that invoked it, therefore, a call to this within a function refers to the invoking object.

Since the context is really important to our understanding of this, we need to know how/why the context switches during runtime:

How does the context change?

The current execution context in a JavaScript program usually points to the object that invokes a function and can be switched to another object by invoking the function with another object.

Call-Site

The place where a function is invoked in a JavaScript program is called the call-site. This is also important in determining the value of this because if the function isn’t invoked by any visible object, the current context of the call-site would be responsible for setting the new execution context of the function.

In simpler terms, the value of this represents the context of the initial executing function in a call-site and remains the same in any other call-site an invoking function doesn’t provide context.

We can finally define this based on all of the explanations presented above:

The value of the this keyword is dependent on the object upon which it is invoked and not the function itself or the function’s scope.

The call-site of the function is also important in determining what this refers to.

This bindings

There are four bindings that are important in determining the value of this in a JavaScript program. We will look at them in this section.

Default binding

Let’s say we were writing a program and defined a function where we used the this keyword, then we invoked the function in the global scope (outside of any function) of the program. What object do you think the this keyword would reference runtime? Let’s see:

let randomFunction = () => {
  this.attribute = 'This is a new attribute to be created on the invoking object';
  console.log(this);
}

randomFunction();

Good thinking! This references the global object in the output below:

In the code above, we created a random function that attaches a new property “attribute” to whichever object invokes it. Because the call-site of the function invocation had its context referencing the global object (this is default), we see that in the output, the console logs a lot of properties that are attached to the global object (Window object) including the property that was created by the random function.

This is the default binding of this in JavaScript. When a function is called without an object, this is by default bound to the current execution context, we will look at the other bindings below.

By default, this is bound to the global object when invoked by a global function.

It is noteworthy that when we are coding in strict mode, this holds the value of undefined in global functions and in anonymous functions that are not bound to any object.

Explicit Binding

Remember how we said that the execution context can be changed by invoking a function on an object? Well, there are explicit ways to easily achieve the same result, let’s look at them briefly:

  • Bind: This method creates a new function and when invoked sets its ‘this’ keyword to a provided value (passed as an argument).
  • Call – This method calls a function and allows us to specify the context its this value should be bound to as an argument. This method accepts optional arguments.
  • Apply – This function is similar to call() with a difference of allowing us to pass in arguments as an array.

Let’s look at an example:

let randomFunction = () => {
  console.log(this);
}

let newObj = {
  description : "This is a new Object"
}

console.log(randomFunction.bind(newObj)());
console.log(randomFunction.call(newObj));
console.log(randomFunction.apply(newObj));

In the code above, we have explicitly bound this in the random function to the newObj variable and we can see that the call, bind and apply methods are available on the Function prototype in JavaScript. They are all correctly bound in the output below:

Implicit Binding

When an object defines a method (that calls this) as a property and calls that method somewhere in a program, the this within the method will be implicitly bound to that object. Let’s look at this example:

let newObj = {
  description : "This is a new Object",
  randomFunction(){
  console.log(this);
  }
}

newObj.randomFunction();

This is a straightforward example that complies with our definition of this above; the invoking object is implicitly bound to the method here and it logs the object when invoked:

New Binding

If we have an object constructor and create a new object with it, the new object will have its this value as a reference to the constructor from which it was created. This is the this binding that happens when a new object is created using a constructor. Let’s look at an example:

function newObj() {
  this.description = "This is an object constructor"

  this.randomFunction = () => {
  console.log(this);
  }  
}

let anotherFunction = new newObj()
anotherFunction.randomFunction()

In the snippet above, we defined a new constructor function and gave it description and randomFunction property and method respectively. We created an instance with the anotherFunction variable and invoked its randomFunction method, here’s the output:

Here, the logged object has the description property that was defined on the object constructor to prove that this references the constructor function.

This and That

The takeaway from everything that has been shown above is:

Wherever this is defined in a function, it usually isn’t assigned a value until an object invokes the containing function.

You might think that the paragraph above is all you would ever need to refer to when you work with this but there are scenarios where this behaves in a weird way (cus JavaScript).

Let’s look at a code snippet where we define a closure that references this in JavaScript:

let newObj = {
  description : "This is a new Object",

  randomFunction(){
    let a = 1

    return function() {
      console.log(this);
    }
  }
}

newObj.randomFunction()();

You would reasonably expect that the closure returns the value of this as the object that invoked randomFunction but let’s see what the output says:

Wait, what? How does this refer to the global object here?
Wasn’t the outer function called by the newObj object?
Shouldn’t that have switched the execution context and updated the this reference?

These are all valid questions, however, here’s something to note:

Closures cannot access their outer function’s this value by calling this within themselves.

This is because the this value of a function is only accessible by the function within which it is encountered and not its inner functions. Hence the this of an anonymous closure will be bound to the global object where strict mode is not being used.

How can we get the preferred behavior?

Here’s a trick. Consider this code snippet:

var newObj = {
  description : "This is a new Object",
  randomFunction(){
    var that = this;

    return function() {
      console.log(that);
    }
  }
}

newObj.randomFunction()();

Here, in randomFunction we declare a new variable called that and assign it the value of this. This way, we can reference the this value of the outer function within the closure since the scope of an outer function is always accessible by its inner functions.

Here’s the output:

Great! We have referenced the this value of the outer function in the closure by creating a that variable.

It should be noted that we could have called the variable anything at all but chose that because so many JavaScript developers already find it convenient to call it that. I sometimes choose cat or thanos hehe.

Now you know this… and that.

Conclusion

We have explored the this keyword in JavaScript clarifying its behavior and use in the process. We also looked at the scenario of closures where the this logic may be elusive and we went over a fitting solution, however, there are situations where this can still prove tricky, the best way to figure it out is to identify which of the bindings is in operation during the function execution and trace back the context carefully. Feel free to leave your feedback and comments. Happy coding!!

Source:: scotch.io

The Node.js Update - #Week 28 - 13 July, 2018

By Tamas Kadlecsik

The Node.js Update - #Week 28 - 13 July, 2018

Below you can find RisingStack‘s collection of the most important Node.js news, updates & tutorials from this week:

Postmortem for Malicious Packages Published on July 12th, 2018

On July 12th, 2018, an attacker compromised the npm account of an ESLint maintainer and published malicious versions of the eslint-scope and eslint-config-eslint packages to the npm registry. On installation, the malicious packages downloaded and executed code from pastebin.com which sent the contents of the user’s .npmrc file to the attacker. An .npmrc file typically contains access tokens for publishing to npm.

We, the ESLint team, are sorry for allowing this to happen. We hope that other package maintainers can learn from our mistakes and improve the security of the whole npm ecosystem.

The malicious package versions are eslint-scope@3.7.2 and eslint-config-eslint@5.0.2, both of which have been unpublished from npm. The pastebin.com paste linked in these packages has also been taken down.

Testing Node.js in 2018

Setting up a good test framework can be tricky regardless of what language you’re using. In this post, we’ll uncover the hard parts of testing with Node.js, the various tooling we decided to utilize in Winds 2.0, and point you in the right direction for when it comes time for you to write your next set of tests.

Node.js REPL in Depth

REPL stands for read-eval-print-loop, or just an interactive session (usually in your terminal), where you can enter some expression and immediately evaluate it, seeing the result. After evaluating, the whole flow repeats, and it works until you exit the process. So, R stands for reading your command, E stands for evaluating it, P stands for printing the result of the execution, and L means to run the whole process again, “in the loop”.

Build and Understand a Simple Node.js Website with User Authentication

Building websites with user authentication and management (login, registration, password reset, etc.), can be a huge pain. As a developer there are a million little things you need to worry about:

  • Storing the users in your database
  • Making sure you have the right user attributes defined
  • Forcing users to be logged in to view a page
  • Building registration and login forms
  • Creating password reset workflows that email users a link
  • Verifying new users when they sign up via email
  • Etc…

Building a Node JS interactive CLI

Node.js can be very useful when it comes to building Command-line Interfaces also known as CLI’s. This post teaches you how to build a CLI that asks some questions and creates a file, based on the answers.

How I built a job scraping web app using Node.js

Indreed is a Rest API for scraping jobs from Indeed and around the web. It is powered by my personal web scraping project and layered on a rest API. Its a real Rest API and can be used from any platform using any programming language.

npm Joins ECMA International and TC39

We’re excited to announce that npm has joined ECMA International and is participating in TC39, the working group of ECMA International that defines the standard for the JavaScript programming language. (The standard is, strictly speaking, called ECMAScript, although everyone refers to it as JavaScript.)

Node.js is Viriciti’s Go-to Dev Platform for Real-time Electric Vehicle Fleet Monitoring

Viriciti, a company focused on electric vehicle fleet monitoring, orchestrates hundreds of thousands of messages per second into real-time dashboards using Node.js, microservices, and serverless. They use Express Gateway, an open source API gateway built on Express.js, to make data available through their API tier.

signale – a hackable console logger for Node.js apps

Hackable and configurable to the core, signale can be used for logging purposes, status reporting, as well as for handling the output rendering process of other node modules and applications.

Previous Node.js Updates:

From the previous Weekly Node.js Update:

  • Node v10.6.0 (Current) Released. Update now!
  • Multi-server Chat in Node Without a Database
  • The Art of Node: An introduction to Node.js
  • Case Study: How Bustle uses Node.js to Speed Up App Development

& more…

We help you to stay up-to-date with Node.js on a daily basis too. Check out our Node.js news page and its Twitter feed!

Source:: risingstack.com