Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the new features in Node.js v14.x LTS

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article will explain in detail what are the new functions in Node.js v14.x LTS, and the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

Optional Chaining (optional chain)

If we use JavaScript, whether it is used in the front end or the Node.js server, the following situation will occur, because we are sometimes not sure whether the user object exists, or whether the address in the user object exists, if we do not judge in this way, we may get similar errors like Cannot read property 'xxx' of undefined.

Const user = {name: 'Tom', address: {city:' ZhengZhou'}} if (user & & user.address) {console.log (user.address.city)}

Now we have an elegant way to write the "optional chain operator" without explicitly verifying whether each reference in the chain is valid with the symbol "?." Indicates that no error will be reported when the reference is null or undefined, and a short circuit will occur to return undefined.

User.address?.city user.address?.city?.length / / access in combination with?. [] is equivalent to user.address ['city'] user.address?. [' city'] / / used in combination with delete statement, and delete delete user.address?.city only if user.address.city exists.

Nullish Coalescing (Null merging)

Logic or operator (| |) returns the operator on the right when the value on the left is false. For example, if we pass an attribute of enabled:0 and we expect to output the value on the left, it will not work.

Function Component (props) {const enable = props.enabled | | true; / / true} Component ({enabled: 0})

Now we can use the * * null merge operator * * to return the value on the right only if the left side is undefined or null.

Function Component (props) {const enable = props.enabled? True; / / 0} Component ({enabled: 0})

Intl.DisplayNames

For the names of languages, regions, currencies, and scripts needed for internationalized applications, JavaScript developers can now use Intl.DisplayNames API to access these translations directly, making it easier for applications to display localized names.

Language (language)

Let longLanguageNames = new Intl.DisplayNames (['zh-CN'], {type:' language'}); longLanguageNames.of ('en-US'); / / US English longLanguageNames.of (' zh-CN'); / / Chinese (China) longLanguageNames = new Intl.DisplayNames (['en'], {type:' language'}); longLanguageNames.of ('en-US'); / / American English longLanguageNames.of (' zh-CN'); / / Chinese (China)

Region (area)

Let regionNames = new Intl.DisplayNames (['zh-CN'], {type:' region'}); regionNames.of ('US'); / / US regionNames.of (' 419'); / / Latin American regionNames = new Intl.DisplayNames (['en'], {type:' region'}); regionNames.of ('US'); / / United States regionNames.of (' 419'); / / Latin America

Currency (currency)

Let currencyNames = new Intl.DisplayNames (['zh-CN'], {type:' currency'}); currencyNames.of ('CNY'); / / RMB currencyNames.of (' USD'); / / US dollar currencyNames = new Intl.DisplayNames (['en'], {type:' currency'}); currencyNames.of ('CNY'); / / Chinese Yuan currencyNames.of (' USD'); / / US Dollar

Script (script)

Let scriptNames = new Intl.DisplayNames (['zh-CN'], {type:' script'}); scriptNames.of ('Hans'); / / simplified scriptNames.of (' Latn'); / / Latin scriptNames = new Intl.DisplayNames (['en'], {type:' script'}); scriptNames.of ('Hans'); / / Simplified scriptNames.of (' Latn'); / / Latin

Intl.DateTimeFormat

The date format used by Intl.DateTimeFormat API to handle a specific locale.

Const date = new Date () / / Sunday, January 10, 2021 at 9:02:29 PM GMT+8 new Intl.DateTimeFormat ('en-US', {dateStyle:' full', timeStyle: 'long'}) .format (date) / / 21-1-10 9pm zh-CN', 02PM GMT+8 new Intl.DateTimeFormat 29.315 new Intl.DateTimeFormat (month:' numeric', day: 'numeric', hour:' numeric', minute: 'numeric') Second: 'numeric', fractionalSecondDigits: 3, timeZoneName:' long'}) .format (date)

String.prototype.matchAll

MatchAll () returns a result that contains all the matching regular expressions, and the return value is an iterator that is not reusable (which means you need to get it again after reading it).

The matchAll () method, which is supported in Node.js v12.4.0 and above, has a restriction that if the set regular expression does not contain the global pattern g, a TypeError exception will be thrown if it is not provided after Node.js v14.5.0.

/ / const regexp = RegExp ('Foo [a-z] *','g'); / / correct const regexp = RegExp ('Foo [a-z] *'); / / error, no global mode const str = 'table football, foosball, fo'; const matches = str.matchAll (regexp); / / TypeError: String.prototype.matchAll called with a non-global RegExp argument for (const item of matches) {console.log (item);}

AsyncLocalStorage

The Node.js Async Hooks module provides the declaration cycle that API uses to track asynchronous resources in Node.js programs. In the latest version of v14.x LTS, a new AsyncLocalStorage class is added to facilitate context-local storage and share data between asynchronous calls, which is useful for implementing log link tracing scenarios.

The following is a simple example of an HTTP request that simulates asynchronous processing and tracks the stored id during log output.

Const http = require ('http'); const {AsyncLocalStorage} = require (' async_hooks'); const asyncLocalStorage = new AsyncLocalStorage (); function logWithId (msg) {const id = asyncLocalStorage.getStore (); console.log (`${id! = = undefined? Id:'-'}: `, msg);} let idSeq = 0; http.createServer ((req, res) = > {asyncLocalStorage.run (idSeq++, ()) = > {logWithId ('start'); setImmediate () = > {logWithId (' processing...'); setTimeout (() = > {logWithId ('finish'); res.end ();}, 2000)});})

Here is the result of the run. I called the second time directly after the first call, and you can see that the id information we stored was successfully printed out along with our log.

Image.png

ES Modules support

ES Modules support is generally a good thing, further standardizing the module ecology of Node.js and browsers, making it more convergent, while avoiding further fragmentation.

Experimental support has been removed in the current version of Node.js v14.x LTS, and there is no need to use flags now. It uses the import and export keywords in two ways:

Use the .mjs extension

/ / caculator.mjs export function add (a, b) {return a + b;}; / / index.mjs import {add} from'. / caculator.js'; console.log (add (4,2)); / / 6

Tell Node.js to treat JavaScript code as ES Modules

By default, Node.js treats JavaScript code as the CommonJS specification, so we will declare it with a .mjs extension above. In addition, we can also set the type field to module in the package.json file or add a flag when running node-input-type=module tells Node.js to treat JavaScript code as ES Modules.

/ / package.json {"name": "esm-project", "type": "module",...}

Students at the front end may be familiar with the above ways of using ES Modules.

Top-Level Await

The top-level await supports the use of the await keyword outside of asynchronous functions, the experimental support has been removed from the Node.js v14.x LTS version, and flags are no longer required for use.

Import fetch from 'node-fetch'; const res = await fetch (url)

You can also import the module dynamically as if you were calling a function.

Const myModule = await import ('. / my-module.js')

For asynchronous resources, we must use await in the async function before, which may not work well for some resources that need to be instantiated at the top of the file. Now with the top-level await, we can easily initialize these asynchronous resources at the top of the file.

Diagnostic report (Diagnostic report)

Diagnostic report is a stable feature provided by Node.js v14.x LTS, which in some cases generates a diagnostic report in JSON format that can be used in development, testing, and production environments. The report will provide valuable information, including JavaScript and native stack information, heap statistics, platform information, resource usage, and so on, to help users quickly track problems.

Report-toolkit is a tool developed by IBM to simplify the use of the reporting tool. Here is a simple Demo that can cause memory leaks in the service.

Const total = []; setInterval (function () {total.push (new Array (20 * 1024 * 1024)); / / large memory footprint, will not be released}, 1000)

The result of the resulting JSON report diagnosed by the report-toolkit tool may be as follows.

Image.png

Stream

The new version includes changes to Stream designed to improve the consistency of Stream API to disambiguate and simplify the behavior of core parts of Node.js, such as:

Http.OutgoingMessage is similar to stream.Writable

Net.Socket behaves exactly the same as stream.Duplex

A significant change the default value of autoDestroy is true, so that the stream always calls _ destroy after it ends.

Use an asynchronous iterator

It's interesting to use an asynchronous iterator to traverse events in Node.js, Stream, or MongoDB return data, although it's not a new feature in Node.js v14.x, for example, event.on is supported in Node.js v12.16.0, which we haven't seen much so far, so I'd like to make a brief introduction here.

Use in Events

The events.on (emitter, eventName) method has been added in Node.js v12.16.0, which returns an asynchronous iterator for iterating eventName events. For example, starting a Node.js service can be written as follows. For those who want to know its principle, please refer to the following article.

Import {createServer as server} from 'http'; import {on} from' events'; const ee = on (server (). Listen (3000), 'request'); for await (const [{url}, res] of ee) if (url = =' / hello') res.end ('Hello Node.jsgiving'); else res.end ('OKboat')

Use in Stream

In the past, we can read data by event listening through on ('data'), which can be done in a simpler way through asynchronous iterators.

Async function readText (readable) {let data ='; for await (const chunk of readable) {data + = chunk;} return data;}

At present, there is no built-in object with the [Symbol.asyncIterator] property set by default in JavaScript. It can be used in some modules of Node.js, Events and Stream. In addition, you can also use it to traverse the returned results of MongoDB.

This is the end of the new features in Node.js v14.x LTS. I hope the above content can be helpful to you and learn more. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report