


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.
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

What is front-end ESM? Specific code examples are required. In front-end development, ESM refers to ECMAScriptModules, a modular development method based on the ECMAScript specification. ESM brings many benefits, such as better code organization, isolation between modules, and reusability. This article will introduce the basic concepts and usage of ESM and provide some specific code examples. The basic concept of ESM In ESM, we can divide the code into multiple modules, and each module exposes some interfaces for other modules to

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces
