Two days ago, Node.js officially released the official version of Node.js 15. Node.js 15 will replace Node.js 14 as the current stable release, which will be upgraded to LTS later this month. If you want to check out the latest features of Node.js 15, you can download them from the official website.

What new features and features does Node.js 15 bring? It is mainly reflected in the following aspects:

  • AbortController
  • N – API version 7
  • npm 7
  • Unhandled rejections is thrown by default
  • QUIC
  • V8 8.6

AbortController

The AbortController interface represents a controller object that allows developers to abort one or more Web requests as needed. Node.js 15 adds an experimental implementation of AbortController. AbortController is a global utility class that cancellations request signaling in selected Promise-based APIS according to the AbortController Web API, as shown below.

const ac = new AbortController();
ac.signal.addEventListener('abort'.() = > console.log('Aborted! '),
{ once: true });
ac.abort();
console.log(ac.signal.aborted);    //Prints True
Copy the code

In the example above, abort is emitted when the abortController.Abort () method is called, abortController fires the abort event only once. Also, event listeners attached to AbortSignal should use the {once: true} parameter option (or once() equivalent to the EventEmitterAPI) to ensure that the event listener is removed once the ABORT event is processed.

AbortController node.js API documentation: AbortController.

N-API 7

N-api is an API for building native plug-ins, independent of the underlying JavaScript runtime environment (such as V8) and as part of Node.js itself. This API will serve as a stable version (ABI) of the Application Binary Interface compiled across Node.js versions. It is designed to isolate the Addons plug-in from changes to the underlying JavaScript engine, and to allow modules compiled in one version to run on higher versions of Node.js without recompiling.

N-api is a C API that ensures the stability of the application program interface (ABI) between Node.js versions and different compiler levels. The C++ API is easier to use. To support the use of C++, node.js uses a C++ wrapper module called node-addon-api, which provides an inline C++ API. Binaries built using Node-Addon-API will rely on the n-API interface based on the C function notation exported by Node.js. Node-addon-api is a more efficient way of writing code to write calls to n-API.

For node.js n-API, see C/C++ addons with n-API

Here is an example of node-addon-API use.

Object obj = Object::New(env);
obj["foo"] = String::New(env, "bar");
Copy the code
napi_status status;
napi_value object, string;
status = napi_create_object(env, &object);
if(status ! = napi_ok) { napi_throw_error(env, ...) ;return;
}

status = napi_create_string_utf8(env, "bar", NAPI_AUTO_LENGTH, &string);
if(status ! = napi_ok) { napi_throw_error(env, ...) ;return;
}

status = napi_set_named_property(env, object, "foo", string);
if(status ! = napi_ok) { napi_throw_error(env, ...) ;return;
}
Copy the code

This update to N-API 7 is the first new release since the last major release, bringing ArrayBuffers with it.

npm 7

Node.js 15 ships with the new large version of NPM, NPM 7. NPM 7 has many new features, including NPM workspaces and the new package-lock.json format. NPM 7 also includes yarn.lock file support. One big change in NPM 7 is that peer dependencies are installed by default.

Unhandled rejections is thrown by default

Starting with Node.js 15, the default mode of unhandledRejection has changed to throw (previously warn). In throw mode, if the unhandledRejection hook is not set, the unhandledRejection will be promoted to an uncaught exception. Users with unhandledRejection hooks should not see any behavior changes and can still switch modes using the –unhandled-rejections=mode process flag.

Before the Node. Js multiple versions of the default UnhandledPromiseRejectionWarning, and according to the Node. Js user insights: As a result of the Unhandled Promise Rejections investigation, Node.js TSC agreed to switch mode to Throw.

QUIC

QUIC is a UDP – based Internet Transport layer protocol developed by Google. It is the basic transport protocol of HTTP/3. And, in November 2016, the Internet Engineering Task Force (IETF) held the first QUIC working group meeting, which was widely concerned by the industry, indicating that QUIC began to take a key step in becoming a new generation of transport layer protocol. Meanwhile, QUIC has built-in TLS 1.3 security, flow control, error correction, connection migration, and multiplexing.

Node.js 15 comes with experimental support for QUIC, which can be enabled by compiling Node.js with the — experimental-Quic configuration flag. For example, the core NET module exposes the Node.js QUIC implementation as follows.

const { createQuicSocket } = require('net');
Copy the code
'use strict';

const key = getTLSKeySomehow();
const cert = getTLSCertSomehow();

const { createQuicSocket } = require('net');

// Create the QUIC UDP IPv4 socket bound to local IP port 1234
const socket = createQuicSocket({ endpoint: { port: 1234}}); socket.on('session'.async (session) => {
  // A new server side session has been created!

  // The peer opened a new stream!
  session.on('stream'.(stream) = > {
    // Let's say hello
    stream.end('Hello World');

    // Let's see what the peer has to say...
    stream.setEncoding('utf8');
    stream.on('data'.console.log);
    stream.on('end'.() = > console.log('stream ended'));
  });

  const uni = await session.openStream({ halfOpen: true });
  uni.write('hi ');
  uni.end('from the server! ');
});

// Tell the socket to operate as a server using the given
// key and certificate to secure new connections, using
// the fictional 'hello' application protocol.
(async function() {
  await socket.listen({ key, cert, alpn: 'hello' });
  console.log('The socket is listening for sessions! '); }) ();Copy the code

For more information about QUIC, refer to the following documentation: QUIC.

V8 8.6

The V8 JavaScript engine has been updated to V8 8.6 (V8 8.4 is the latest version in Node.js 14). In addition to performance tweaks and improvements, the V8 update brings the following language features:

Promise. Any () – the MDN

Promise.any() receives a Promise iterable and returns the Promise that succeeded as soon as one of the promises succeeds. If none of the promises in the iterable succeed (i.e. all Promises fail/reject), return an instance of the failed promise and AggregateError type, which is a subclass of Error and is used to group single errors together.

The reference documentation for promise.any () looks like this: promise.any ()

AggregateError – MDN

AggregateError is mainly used for scenarios where multiple errors are reported and the syntax is as follows:

new AggregateError(errors[, message])
Copy the code

Example code for catching an AggregateError is as follows:

Promise.any([
  Promise.reject(new Error("some error")),
]).catch(e= > {
  console.log(e instanceof AggregateError); // true
  console.log(e.message);                   // "All Promises rejected"
  console.log(e.name);                      // "AggregateError"
  console.log(e.errors);                    // [ Error: "some error" ]
});
Copy the code

Example code for creating an AggregateError is as follows:

try {
  throw new AggregateError([
    new Error("some error")],'Hello');
} catch (e) {
  console.log(e instanceof AggregateError); // true
  console.log(e.message);                   // "Hello"
  console.log(e.name);                      // "AggregateError"
  console.log(e.errors);                    // [ Error: "some error" ]
}
Copy the code

For details, see AggregateError

String. The prototype. The replaceAll () – MDN

The replaceAll() method returns a new string with all parts of the string that satisfy pattern replaced. Pattern can be a string or a RegExp, replacement can be a string or a function that is called each time a match is made.

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy? ';

const regex = /dog/gi;

console.log(p.replaceAll(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"

console.log(p.replaceAll('dog'.'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"

Copy the code

Detailed reference: String. Prototype. ReplaceAll ()

Amway upgrade

Plus, with the new release of Node.js 15! Developers are expected to upgrade as soon as possible and report any problems they encounter to the authorities. Of course, developers can also use Node.js 15 to test your applications and modules to ensure that your project is compatible with the latest Node.js features and changes.

Also, Node.js is officially planning to upgrade to Node.js 14, which will be upgraded to LTS next week, with support continuing until April 2023. Also note that Node.js 10 will end its life cycle in April 2021. So, if you’re still using Node.js 10, we suggest you start planning for the upgrade.

Medium.com/nodejs/nod…