Home  >  Article  >  Web Front-end  >  The official version of Node.js 15 is released and will replace Node.js 14 as the current stable release.

The official version of Node.js 15 is released and will replace Node.js 14 as the current stable release.

青灯夜游
青灯夜游forward
2020-10-22 19:57:424267browse

The official version of Node.js 15 is released and will replace Node.js 14 as the current stable release.

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. The latter It will be upgraded to an LTS (Long Term Support) version later this month. If you want to experience the latest features of Node.js 15, you can download it from the official website.

The official version of Node.js 15 is released and will replace Node.js 14 as the current stable release.

Video tutorial recommendation: nodejs tutorial

So what new functions and features does Node.js 15 bring? Mainly reflected in the following aspects:

  • AbortController
  • N-API version 7
  • npm 7
  • unhandled rejections are thrown by default
  • QUIC
  • V8 8.6

AbortController

The AbortController interface represents a controller object, allowing 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 cancels outgoing request signals 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

In the above example, the abort event will be emitted when the abortController.abort() method is called, and AbortController will only trigger the abort event once. Also, event listeners attached to the AbortSignal should use the { once: true} parameter option (or equivalent once() of the EventEmitterAPI) to ensure that once the abort event is handled, the event Listener deleted.

For the Node.js API documentation of AbortController, please refer to: AbortController.

N-API 7

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

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

For information about the N-API of Node.js, please refer to: C/C addons with N-API

The following is an example of using node-addon-api.

Object obj = Object::New(env);
obj["foo"] = String::New(env, "bar");
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;
}

This updated N-API 7 is the first new version since the previous major version, and brings related content about ArrayBuffers.

npm 7

Node.js 15 comes with npm’s new major version, npm 7. npm 7 has many new features, including npm workspaces and a new package-lock.json format. npm 7 also includes yarn.lock file support. One of the big changes in npm 7 is the default installation of peer dependencies.

unhandled rejections throw by default

Starting in Node.js 15, the default mode for unhandledRejection has been changed to throw (formerly warn). In throw mode, if the unhandledRejection hook is not set, unhandledRejection will be raised to an uncaught exception. Users with an unhandledRejection hook should not see any change in behavior and can still use the --unhandled-rejections=mode process flag to switch modes.

Many previous versions of Node.js would emit UnhandledPromiseRejectionWarning by default, and according to the results of the "Node.js User Insights: Unhandled Promise Rejections" survey, the Node.js TSC agreed to switch the mode to throw.

QUIC

QUIC is a low-latency Internet transport layer protocol based on UDP developed by Google. It is the basic transport protocol of HTTP/3. Moreover, in November 2016, the International Internet Engineering Task Force (IETF) held the first QUIC working group meeting, which attracted widespread attention from the industry, meaning that QUIC began to take a key step in becoming a new generation transport layer protocol. . QUIC, meanwhile, 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 a Node.js QUIC implementation with the following code.

const { createQuicSocket } = require('net');
'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!');
})();

For more information about QUIC, you can refer to the following document: 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, V8 updates bring the following language features:

Promise.any()——MDN

Promise.any() 接收一个Promise可迭代对象,只要其中的一个 promise 成功,就返回那个已经成功的 promise 。如果可迭代对象中没有一个 promise 成功(即所有的 promises 都失败/拒绝),就返回一个失败的 promise 和AggregateError类型的实例,它是 Error 的一个子类,用于把单一的错误集合在一起。

Promise.any()的参考文档如下所示:Promise.any()

AggregateError——MDN

AggregateError主要用于操作报告多个错误被抛出的场景,语法格式如下:

new AggregateError(errors[, message])

捕获一个AggregateError的示例代码如下:

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" ]
});

创建一个AggregateError的示例代码如下:

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" ]
}

详细参考文档:AggregateError

String.prototype.replaceAll()——MDN

replaceAll() 方法是返回一个新字符串,新字符串所有满足 pattern 的部分都已被replacement 替换。pattern可以是一个字符串或一个 RegExp, replacement可以是一个字符串或一个在每次匹配被调用的函数。

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?"

详细内容参考:String.prototype.replaceAll()

安利升级

另外,随着 Node.js 15 新版本的发布!官方希望开发者尽快的进行升级,并将遇到的问题反馈就给官方,。当然,开发者还可以使用 Node.js 15 测试你的应用程序和模块,以确保你的项目与最新的 Node.js 特性和更改兼容。

并且,Node.js官方也开始计划升级到 Node.js 14 ,它将在下周升级到 LTS,支持会持续到直到 2023 年 4 月。还要注意的是,Node.js 10 将于 2021 年 4 月结束生命周期。因此,如果你仍在使用 Node.js 10,我们建议你开始计划升级。

原文链接:https://medium.com/@nodejs/node-js-v15-0-0-is-here-deb00750f278

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of The official version of Node.js 15 is released and will replace Node.js 14 as the current stable release.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete