What's new in Node 8.0.0

VonRickroll
1,517 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Node 8.0.0 is here! Released on May 30th 2017, It enters Node's Long Term Support roadmap and it brings some new interesting features to the table. The complete release note is available on the official Node blog, but let's take a look at the some of the release highlights.


Promisify

APIs with a standard callback style, such as fs.readFile(path, callback) or request(path, callback) can now be wrapped into promises by using util.promisify(). It creates a function that returns a promise.

Promisify
1
2
3
4
5
6
7
8
9
10
11
12
13
const fs = require('fs');
const util = require('util');
// This will create a "promisified" version of fs.readFile
const readfile = util.promisify(fs.readFile);
readfile('./file-to-read.txt') // This returns a promise
.then((data) => {
console.log(data.toString());
})
.catch((err) => {
console.log(err);
});
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Async Hooks

async_hooks is an experimental module that helps you monitor async operations. You can define hooks for the various stages of an async request's lifecycle. The constructor async_hooks.createHook takes an object as a parameter, which contains a few different callbacks:

// Create a new AsyncHook instance. All of these callbacks are optional.
const asyncHook = async_hooks.createHook({
  init: initCallback,
  before: beforeCallback,
  after: afterCallback,
  destroy: destroyCallback
});
Async Hooks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Adapted from the official documentation at https://github.com/AndreasMadsen/node/blob/82149a8e0f0a13e5f34215e370b6750a300617e6/doc/api/async_hooks.md
const async_hooks = require('async_hooks');
const fs = require('fs');
const util = require('util');
// Some other useful APIs
// Return the ID of the current execution context.
const cid = async_hooks.currentId();
// Return the ID of the handle responsible for triggering the callback of the
// current execution scope to call.
const tid = async_hooks.triggerId();
// Create a new AsyncHook instance. All of these callbacks are optional.
const asyncHook = async_hooks.createHook({ init, before, after, destroy });
// init is called during object construction. The resource may not have
// completed construction when this callback runs, therefore all fields of the
// resource referenced by "asyncId" may not have been populated.
function init(asyncId, type, triggerId, resource) {
debug('Init async hook', asyncId);
}
// before is called just before the resource's callback is called. It can be
// called 0-N times for handles (e.g. TCPWrap), and will be called exactly 1
// time for requests (e.g. FSReqWrap).
function before(asyncId) {
debug('Before async hook', asyncId);
}
// after is called just after the resource's callback has finished.
function after(asyncId) {
debug('After async hook', asyncId);
}
// destroy is called when an AsyncWrap instance is destroyed.
function destroy(asyncId) {
debug('Destroy async hook', asyncId);
}
// Allow callbacks of this AsyncHook instance to call. This is not an implicit
// action after running the constructor, and must be explicitly run to begin
// executing callbacks.
asyncHook.enable();
// Register an asynchronous task
setTimeout((x)=>{
debug('Timeout!');
}, 5000);
// Disable listening for new asynchronous events.
//asyncHook.disable();
function debug() {
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Read the official documentation for async_hooks. Be aware that async_hooks is a work in progress and "users should take great care when using the experimental new module".


URL parser API

Node 8.0.0 now supports the WHATWG URL standard. This helps you parse and handle URL objects easily. There is an official documentation guide for the WHATWG URL methods, but here are some of them.

URL API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const URL = require('url').URL;
const myURL = new URL('https://example.org:8080/foo?first=john&last=doe#bar');
console.log(`## Properties:
href: ${myURL.href}
protocol: ${myURL.protocol}
pathname: ${myURL.pathname}
host: ${myURL.host}
port: ${myURL.port}
hostname: ${myURL.hostname}
hash: ${myURL.hash}
search: ${myURL.search}
`);
// You can also set these properties
myURL.port = 9999;
console.log('New port:', myURL.port);
// Inspecting search parameters
console.log('## Search Parameters:');
const searchParams = myURL.searchParams;
searchParams.forEach((value, name) => {
console.log(name, ':', value);
}
);
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Read the official documentation for the WHATWG URL API.


--pending-deprecation

--pending-deprecation is a new flag that will warn you if your Node program is using features that are pending deprecation. For instance, in Node 8.0.0, the constructor Buffer(num) for the Buffer API (used to create 0-filled Buffer instances) is depreciating. If you continue to use it and launch Node with the --pending-deprecation flag, it will emit a DeprecationWarning warning.

The following snippets runs Node 8.0.0 with the --pending-deprecation flag. Try it out.

Deprecation Warnings
1
2
3
4
// Instanciating a Buffer with Buffer.alloc(num)
const buffer1 = Buffer.alloc(10); // Should run fine
// Instanciating a Buffer with the Buffer(num) constructor
const buffer2 = Buffer(10); // Should emit a DeprecationWarning warning
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

These are the key features in this release but Node 8.0.0 comes with other new features. Have fun checking them out and reading the official release note.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content