Node.js 19正式釋出,聊聊它的 6 大特性!

2022-11-16 22:00:34
19已正式釋出,下面本篇文章就來帶大家詳解了解一下Node.js 19的 6 大特性,希望對大家有所幫助!

node.js極速入門課程:進入學習

通譯自:


Node.js 14 將在 2023 年 4 月結束更新維護,Node.js 16 (LTS) 預計將在 2023 年 9 月結束更新維護。

而Node 19 在 2022-10-18 釋出。【相關教學推薦:】

我們知道 Node.js 版本分兩種:LTS 和 Current

image.png

其中,Current 版本通常每 6 個月釋出一次。

每年 4 月份釋出新的偶數版本;

每年 10 月份釋出新的奇數版本;

在剛過去的 10 月,釋出的 V19.0.1 成為最新的 「Current」 嚐鮮版,它一共帶來 6 大特性。

1. HTTP(S)/1.1 KeepAlive 預設為 true

Node.js v19 設定 keepAlive 預設值為 true,這意味著所有出站的 HTTP(s) 連線都將使用 HTTP 1.1 keepAlive,預設時間為 5S;

程式碼測試:

const http = require('node:http');
console.log(http.globalAgent);
const https = require('node:https');
console.log(https.globalAgent);
登入後複製

我們可以對比看看 v16 和 v19 的 node server Agent 設定差異:

  • 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
}
登入後複製

第 18、40 行,keepAlive 預設設定為 false;

  • 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
}
登入後複製

第 14、16、42、44 行設定 keepAlive 預設值及時間;

啟用 keepAlive 能使連線重用,提高網路的吞吐量。

另外,伺服器將在呼叫 close() 自動斷開空閒的使用者端,內部依靠 http(s).Server.close API 實現;

這些修改,進一步優化了體驗和效能。

2. 穩定的 WebCrypto API

WebCrypto API 是一個使用密碼學構建的系統介面,在 node.js v19 趨於穩定(除 Ed25519、Ed448、X25519、X448 外)。

我們可以通過呼叫 globalThis.cryptorequire('node:crypto').webcrypto 來存取,下面以 subtle 加密函數為例;

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);

})();
登入後複製

首先生成 HMAC 金鑰,生成的金鑰可同時用於驗證訊息資料完整性和真實性;

然後,對字串 I love cupcakes 加密;

最後建立 訊息摘要,它是一種加密雜湊函數;

在控制檯顯示:key 、message 、digest 資訊

% 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. 自定義 ESM resolution 調整

Node.js 已經刪除 --experimental-specifier-resolution ,其功能現在可以通過自定義載入器實現。

可以在這個庫中測試:

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

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

% yarn install
登入後複製

比如 loaders-test/commonjs-extension-resolution-loader/test/basic-fixtures/index.js 檔案:

import { version } from 'process';

import { valueInFile } from './file';
import { valueInFolderIndex } from './folder';

console.log(valueInFile);
console.log(valueInFolderIndex);
登入後複製

./file 如果沒有自定義載入器,不會去查詢檔案的擴充套件名,比如 ./file.js./file.mjs

設定自定義載入器後,則可解決上述問題:

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

import resolveCallback from 'resolve/async.js';

const resolveAsync = promisify(resolveCallback);

const baseURL = pathToFileURL(cwd() + '/').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('file://')) {
    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't search for .mjs extensions
      // but it does search for index.mjs files within directories
      extensions: ['.js', '.json', '.node', '.mjs'],
    });
    url = pathToFileURL(resolution).href;
  } catch (error) {
    if (error.code === 'MODULE_NOT_FOUND') {
      // Match Node's error code
      error.code = 'ERR_MODULE_NOT_FOUND';
    }
    throw error;
  }

  return next(url, context);
}
登入後複製

測試命令:

% 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
登入後複製

將不會再報錯,正常執行。

4. 移除對 DTrace/SystemTap/ETW 支援

在 Node.js v19中,移除了對 DTrace/SystemTap/ETW 的支援,主要是因為資源的優先順序問題。

資料表明很少人用到 DTrace、SystemTap 或 ETW,維護它們沒有多大的意義。

如果你想恢復使用,可提 issues =>

5. 升級 V8 引擎至 10.7

Node.js v19 將 V8 JavaScript 引擎更新至 V8 10.7,其中包含一個新函數 Intl.NumberFormat,用於格式化敏感數位。

Intl.NumberFormat(locales, options)
登入後複製

對於不同的語言,傳入不同的 locales:

const number = 123456.789;

console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));
console.log(new Intl.NumberFormat('ar-SA', { style: 'currency', currency: 'EGP' }).format(number));
console.log(new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(number));
登入後複製

6. 試驗 Node watch 模式

執行時增加了 node --watch 選項。

在 "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相關知識,請存取:!

以上就是Node.js 19正式釋出,聊聊它的 6 大特性!的詳細內容,更多請關注TW511.COM其它相關文章!