Home  >  Article  >  Web Front-end  >  Node.js 19 is officially released, let's talk about its 6 major features!

Node.js 19 is officially released, let's talk about its 6 major features!

青灯夜游
青灯夜游forward
2022-11-16 20:34:481535browse

Node 19 has been officially released. The following article will give you a detailed explanation of the 6 major features of Node.js 19. I hope it will be helpful to everyone!

Node.js 19 is officially released, let's talk about its 6 major features!

Translated from: 6 Major Features of Node.js 19. Details of Node.js 19 new features… | by Jennifer Fu | Oct, 2022 | Better Programming


Node.js 14 will end update maintenance in April 2023, Node.js 16 (LTS) is expected to end update maintenance in September 2023 .

And Node 19 was released on 2022-10-18. [Related tutorial recommendations: nodejs video tutorial]

We know that there are two versions of Node.js: LTS and Current

Node.js 19 is officially released, lets talk about its 6 major features!

Among them , the Current version is usually released every 6 months.

New even-numbered versions are released every April;

New odd-numbered versions are released every October;

In the past October, the released V19.0.1 became the latest The "Current" early adopter version brings a total of 6 major features.

1. HTTP(S)/1.1 KeepAlive defaults to true

Node.js v19 sets the keepAlive default value to true, which means that all outbound HTTP( s) All connections will use HTTP 1.1 keepAlive, and the default time is 5S;

Code test:

const http = require('node:http');
console.log(http.globalAgent);
const https = require('node:https');
console.log(https.globalAgent);

We can compare the node server Agent configuration differences between v16 and v19:

  • V16
% nvm use 16
Now using node v16.0.0 (npm v7.10.0)
% node server
Agent {
  _events: [Object: null prototype] {
    free: [Function (anonymous)],
    newListener: [Function: maybeEnableKeylog]
  },
  _eventsCount: 2,
  _maxListeners: undefined,
  defaultPort: 80,
  protocol: 'http:',
  options: [Object: null prototype] { path: null },
  requests: [Object: null prototype] {},
  sockets: [Object: null prototype] {},
  freeSockets: [Object: null prototype] {},
  keepAliveMsecs: 1000,
  keepAlive : false,
  maxSockets: Infinity,
  maxFreeSockets: 256,
  scheduling: 'lifo',
  maxTotalSockets: Infinity,
  totalSocketCount: 0,
  [Symbol(kCapture)]: false
}
Agent {
  _events: [Object: null prototype] {
    free: [Function (anonymous)],
    newListener: [Function: maybeEnableKeylog]
  },
  _eventsCount: 2,
  _maxListeners: undefined,
  defaultPort: 443,
  protocol: 'https:',
  options: [Object: null prototype] { path: null },
  requests: [Object: null prototype] {},
  sockets: [Object: null prototype] {},
  freeSockets: [Object: null prototype] {},
  keepAliveMsecs: 1000,
  keepAlive: false,
  maxSockets: Infinity,
  maxFreeSockets: 256,
  scheduling: 'lifo',
  maxTotalSockets: Infinity,
  totalSocketCount: 0,
  maxCachedSessions: 100,
  _sessionCache: { map: {}, list: [] },
  [Symbol(kCapture)]: false
}

Lines 18 and 40, keepAlive is set to false by default;

  • V19
% nvm use 19
Now using node v19.0.0 (npm v8.19.2)
% node server
Agent {
  _events: [Object: null prototype] {
    free: [Function (anonymous)],
    newListener: [Function: maybeEnableKeylog]
  },
  _eventsCount: 2,
  _maxListeners: undefined,
  defaultPort: 80,
  protocol: 'http:',
  options: [Object: null prototype] {
    keepAlive: true,
    scheduling: 'lifo',
    timeout: 5000,
    noDelay: true,
    path: null
  },
  requests: [Object: null prototype] {},
  sockets: [Object: null prototype] {},
  freeSockets: [Object: null prototype] {},
  keepAliveMsecs: 1000,
  keepAlive: true,
  maxSockets: Infinity,
  maxFreeSockets: 256,
  scheduling: 'lifo',
  maxTotalSockets: Infinity,
  totalSocketCount: 0,
  [Symbol(kCapture)]: false
}
Agent {
  _events: [Object: null prototype] {
    free: [Function (anonymous)],
    newListener: [Function: maybeEnableKeylog]
  },
  _eventsCount: 2,
  _maxListeners: undefined,
  defaultPort: 443,
  protocol: 'https:',
  options: [Object: null prototype] {
    keepAlive: true,
    scheduling: 'lifo',
    timeout: 5000,
    noDelay: true,
    path: null
  },
  requests: [Object: null prototype] {},
  sockets: [Object: null prototype] {},
  freeSockets: [Object: null prototype] {},
  keepAliveMsecs: 1000,
  keepAlive: true,
  maxSockets: Infinity,
  maxFreeSockets: 256,
  scheduling: 'lifo',
  maxTotalSockets: Infinity,
  totalSocketCount: 0,
  maxCachedSessions: 100,
  _sessionCache: { map: {}, list: [] },
  [Symbol(kCapture)]: false
}

Line 14 , Lines 16, 42, and 44 set the keepAlive default value and time;

Enabling keepAlive can reuse connections and improve network throughput.

In addition, the server will automatically disconnect the idle client when calling close(), which is implemented internally by relying on the http(s).Server.close API;

These modifications further optimize the experience and performance.

2. Stable WebCrypto API

WebCrypto API is a system interface built using cryptography, which tends to be stable in node.js v19 (except Ed25519, Ed448, Except X25519 and X448).

We can access it by calling globalThis.crypto or require('node:crypto').webcrypto, the following is the subtle encryption function For example;

const { subtle } = globalThis.crypto;

(async function() {

  const key = await subtle.generateKey({
    name: 'HMAC',
    hash: 'SHA-256',
    length: 256
  }, true, ['sign', 'verify']);

  console.log('key =', key);

  const enc = new TextEncoder();
  const message = enc.encode('I love cupcakes');

  console.log('message =', message);

  const digest = await subtle.sign({
    name: 'HMAC'
  }, key, message);

  console.log('digest =', digest);

})();

First generate the HMAC key, and the generated key can be used to verify the integrity and authenticity of the message data;

Then, for the string I love cupcakes Encryption;

Finally create a message digest, which is an encrypted hash function;

Display on the console: key, message, digest information

% node server
key = CryptoKey {
  type: 'secret',
  extractable: true,
  algorithm: { name: 'HMAC', length: 256, hash: [Object] },
  usages: [ 'sign', 'verify' ]
}
message = Uint8Array(15) [   73, 32, 108, 111, 118,  101, 32,  99, 117, 112,   99, 97, 107, 101, 115]
digest = ArrayBuffer {
  [Uint8Contents]: <30 01 7a 5c d9 e2 82 55 6b 55 90 4f 1d de 36 d7 89 dd fb fb 1a 9e a0 cc 5d d8 49 13 38 2f d1 bc>,
  byteLength: 32
}

3. Custom ESM resolution adjustment

Node.js has been removed --experimental-specifier-resolution , and its functionality can now be achieved through a custom loader.

Can be tested in this library: nodejs/loaders-test: Examples demonstrating the Node.js ECMAScript Modules Loaders API

git clone https://github.com/nodejs/loaders-test.git

% cd loaders-test/commonjs-extension-resolution-loader

% yarn install

For exampleloaders-test/ commonjs-extension-resolution-loader/test/basic-fixtures/index.js File:

import { version } from &#39;process&#39;;

import { valueInFile } from &#39;./file&#39;;
import { valueInFolderIndex } from &#39;./folder&#39;;

console.log(valueInFile);
console.log(valueInFolderIndex);

./file If there is no custom loader, the file will not be found extension, such as ./file.js or ./file.mjs

After setting a custom loader, the above problem can be solved:

import { isBuiltin } from &#39;node:module&#39;;
import { dirname } from &#39;node:path&#39;;
import { cwd } from &#39;node:process&#39;;
import { fileURLToPath, pathToFileURL } from &#39;node:url&#39;;
import { promisify } from &#39;node:util&#39;;

import resolveCallback from &#39;resolve/async.js&#39;;

const resolveAsync = promisify(resolveCallback);

const baseURL = pathToFileURL(cwd() + &#39;/&#39;).href;


export async function resolve(specifier, context, next) {
  const { parentURL = baseURL } = context;

  if (isBuiltin(specifier)) {
    return next(specifier, context);
  }

  // `resolveAsync` works with paths, not URLs
  if (specifier.startsWith(&#39;file://&#39;)) {
    specifier = fileURLToPath(specifier);
  }
  const parentPath = fileURLToPath(parentURL);

  let url;
  try {
    const resolution = await resolveAsync(specifier, {
      basedir: dirname(parentPath),
      // For whatever reason, --experimental-specifier-resolution=node doesn&#39;t search for .mjs extensions
      // but it does search for index.mjs files within directories
      extensions: [&#39;.js&#39;, &#39;.json&#39;, &#39;.node&#39;, &#39;.mjs&#39;],
    });
    url = pathToFileURL(resolution).href;
  } catch (error) {
    if (error.code === &#39;MODULE_NOT_FOUND&#39;) {
      // Match Node&#39;s error code
      error.code = &#39;ERR_MODULE_NOT_FOUND&#39;;
    }
    throw error;
  }

  return next(url, context);
}

Test command:

% node --loader=./loader.js test/basic-fixtures/index  
(node:56149) ExperimentalWarning: Custom ESM Loaders is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
hello from file.js

will no longer report errors and run normally.

4. Removed support for DTrace/SystemTap/ETW

In Node.js v19, support for DTrace/SystemTap/ETW has been removed, mainly Because of resource priority issues.

The data shows that few people use DTrace, SystemTap or ETW, and there is not much point in maintaining them.

If you want to resume use, you can file issues => github.com/nodejs/node…

5. Upgrade the V8 engine to 10.7

Node.js v19 updates the V8 JavaScript engine to V8 10.7, which includes a new function Intl.NumberFormat for formatting sensitive numbers.

Intl.NumberFormat(locales, options)

For different languages, pass in different locales:

const number = 123456.789;

console.log(new Intl.NumberFormat(&#39;de-DE&#39;, { style: &#39;currency&#39;, currency: &#39;EUR&#39; }).format(number));
console.log(new Intl.NumberFormat(&#39;ja-JP&#39;, { style: &#39;currency&#39;, currency: &#39;JPY&#39; }).format(number));
console.log(new Intl.NumberFormat(&#39;ar-SA&#39;, { style: &#39;currency&#39;, currency: &#39;EGP&#39; }).format(number));
console.log(new Intl.NumberFormat(&#39;zh-CN&#39;, { style: &#39;currency&#39;, currency: &#39;CNY&#39; }).format(number));

6. Experiment with Node watch mode

Added node during runtime -- watch option.

在 "watch" 模式下运行,当导入的文件被改变时,会重新启动进程。

比如:

const express = require("express");
const path = require("path");
const app = express();
app.use(express.static(path.join(__dirname, "../build")));

app.listen(8080, () =>
  console.log("Express server is running on localhost:8080")
);
% node --watch server
(node:67643) ExperimentalWarning: Watch mode is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
Express server is running on localhost:8080

Node.js 14 将在 2023 年 4 月结束更新维护,Node.js 16 (LTS) 预计将在 2023 年 9 月结束更新维护。

建议大家开始计划将版本按需升级到 Node.js 16(LTS)或 Node.js 18(LTS)。

更多node相关知识,请访问:nodejs 教程

The above is the detailed content of Node.js 19 is officially released, let's talk about its 6 major features!. For more information, please follow other related articles on the PHP Chinese website!

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