44

Node.js v12 - New Features You Shouldn't Miss

 5 years ago
source link: https://www.tuicool.com/articles/hit/IFfUNnr
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Node.js v12 is out on schedule ! It is going into LTS in October and will be maintained until 2022.

Here is a list of changes we consider essential to highlight:

  • V8 updated to version 7.4
    • Async stack traces arrived (more info..)
    • Faster async/await implementation (more info..)
    • New JavaScript language features
    • Performance tweaks & improvements (more info..)
    • Progress on Worker threads, N-API
  • Default HTTP parser switched to llhttp
  • New experimental “Diagnostic Reports” feature

You can browse the full changelog here .

FYI: Back then we broke down the new features in Node.js v10 which you can readhere.

assert module adjustments in Node 12

Let’s start with one of the most neglectable but important adjustment in the assert module. Starting from v12.0.0 the assertion methods validate the required arguments.

YFRrain.png!web v11.14.0

V3AVN3V.png!web v12.0.0

Instead of returning a misleading ERR_ASSERTION error, the methods indicate if there are arguments missing with the ERR_MISSING_ARGS error code.

Error messages got an update as well which remind us all to always use the error code to check for specific failures in the code base.

TLS 1.3 is now default in Node.js 12

TLS 1.3 is now the default max protocol supported by Node.js.

After 8 years, TLS has been updated and it offers enhanced security and performance. Support for RSA has been removed because of its history of bugs and it also did not support forward secrecy. The protocol also got safer cipher options and modes while halved the number of handshake roundtrips contrary to its 1.2 predecessor which required two roundtrips.

JavaScript language features in Node 12

Let's go one by one..

Async stack traces

So far, developers faced the problem of V8 truncating the stack trace up to the most recent await . Thanks to a recent update to the engine, Node.js now tracks the asynchronous call frames in the error.stack property.

async function wait_1(x) {
 await wait_2(x)
}

async function wait_2(x) {
 await wait_3(x);
}

async function wait_3(x) {
 await x;

 throw new Error("Oh boi")
}

wait_1(1).catch(e => console.log(e.stack));

This code example prints the following outputs before and after async stack traces got into Node.js.

ZNRb6rn.png!web v11.14.0

6VZzYjU.png!web v12.0.0

Public class fields

Instead of listing all variables with default values in the constructor, you can define them on the class level.

class Vehicle {
 constructor(type) {
   this.type = type;
   this.speed = 80;
 }
}

Thus, you can omit the constructor if no parameter is needed or just focus on the required variables on initialization.

class Vehicle2 {
 speed = 80;

 constructor(type) {
   this.type = type;
 }
}

Private class fields

JavaScript brought in the concept of private class fields which finally landed in Node.js v12. To mark fields private just give them a name starting with # .

class Counter {
 #count = 0

 increment() {
   this.#count++;
 }

 get value() {
   return this.#count;
 }
}

const counter = new Counter()
counter.increment()
counter.value // 1

counter.#value // SyntaxError

Watch out, if You try to access a private field outside of the class it throws a SyntaxError error!

llhttp parser in Node.js 12

llhttp is a port of http_parser that improves on maintainability and benchmark results. The library claims to be faster by 116%.

The implementation was first introduced in v11.2.0 and it will be taken out from experimental in this release.

Diagnostic Reports

This utility tool is known as node-report that was recently brought into the Node.js core. It helps to detect abnormal terminations, memory leaks, high CPU usage, unexpected errors and more.

Run the node --experimental-report --report-on-fatalerror index.js to get a JSON summary on native stack traces, heap statistics, resource usage, etc.

$ node --help | grep report

 --experimental-report       enable report generation
 --report-directory=...      define custom report pathname.
 --report-filename=...       define custom report file name.
 --report-on-fatalerror      generate diagnostic report on fatal
 --report-on-signal          generate diagnostic report upon
 --report-signal=...         causes diagnostic report to be produced
 --report-uncaught-exception generate diagnostic report on uncaught

Node.js got a bunch of diagnostic utilities in the recent versions to aid the investigation on errors and bottlenecks that are difficult to pinpoint. If you want to create runtime statistics of the heap usage you can do that by calling v8.getHeapSnapshot() that was added in v11.13.0.

Worker threads in Node 12

The worker_threads module got into Node.js in v10.5.0. It’s still in experimental but a lot of effort has gone into its progress.

Node.js was designed single-threaded which fits I/O heavy use cases well. CPU heavy operations, however, increase execution time and lead to slow performance.

PSA: If you're facing performance problems with Node, reach out to us!

Now, 12factor says that these long-running operations should be offloaded to individual processes. However, this might not be a valid solution, when you need to expose the result of CPU heavy computations such as data-mining and crypto over HTTP. Workers open the possibility to utilize more threads at once to execute these actions parallel.

It’s not a stable solution though but it might be game-changing for the Node.js community. Workers offer Node.js an opportunity to become a player on the field of data science beside R, Scala, Python and more.

Get started with Node.js v12

You can download the latest Node.js version here .

Support Node.js by reporting issues you bump into!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK