ホームページ  >  記事  >  ウェブフロントエンド  >  Node.js 19 が正式リリースされました。その 6 つの主要な機能についてお話しましょう。

Node.js 19 が正式リリースされました。その 6 つの主要な機能についてお話しましょう。

青灯夜游
青灯夜游転載
2022-11-16 20:34:481460ブラウズ

Node 19 が正式リリースされました。次の記事では Node.js 19 の 6 つの主要な機能について詳しく説明します。皆様のお役に立てれば幸いです。

Node.js 19 が正式リリースされました。その 6 つの主要な機能についてお話しましょう。

翻訳元: 6 Node.js の主な機能 19. Node.js 19 の新機能の詳細… | Jennifer Fu 著 | 2022 年 10 月| より良いプログラミング


Node.js 14 は 2023 年 4 月に更新メンテナンスが終了し、Node.js 16 (LTS) は 2023 年 9 月に更新メンテナンスが終了する予定です。

そして、ノード 19 は 2022 年 10 月 18 日にリリースされました。 [関連チュートリアルの推奨事項: nodejs ビデオ チュートリアル ]

Node.js には、LTS と Current の 2 つのバージョンがあることがわかっています。

Node.js 19 が正式リリースされました。その 6 つの主要な機能についてお話しましょう。

# #そのうち、現行バージョンは通常 6 か月ごとにリリースされます。

新しい偶数番号のバージョンは毎年 4 月にリリースされます;

新しい奇数番号のバージョンは毎年 10 月にリリースされます;

昨年 10 月にリリースされた V19.0.1 は、最新の「現在の」早期採用バージョンには、合計 6 つの主要な機能が含まれています。

1. HTTP(S)/1.1 KeepAlive のデフォルト値は true

Node.js v19 は keepAlive のデフォルト値を true に設定します。これは、すべてのアウトバウンド HTTP( s ) すべての接続は HTTP 1.1 keepAlive を使用し、デフォルト時間は 5 秒です;

コード テスト:

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

v16 と 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
    }
行 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 を有効にすると、接続を再利用し、ネットワーク スループットを向上させることができます。

さらに、サーバーは、

http(s).Server.close## に依存して内部実装されている close() を呼び出すと、アイドル状態のクライアントを自動的に切断します。 # API; これらの変更により、エクスペリエンスとパフォーマンスがさらに最適化されます。

2. 安定した WebCrypto API

WebCrypto API は、暗号化を使用して構築されたシステム インターフェイスであり、node.js v19 で安定する傾向があります (Ed25519、Ed448 を除く)。 X25519 および X448)。

globalThis.crypto

または require('node:crypto').webcrypto を呼び出すことでアクセスできます。以下は 微妙なです。暗号化関数 例; <pre class="brush:js;toolbar:false;">const { subtle } = globalThis.crypto; (async function() { const key = await subtle.generateKey({ name: &amp;#39;HMAC&amp;#39;, hash: &amp;#39;SHA-256&amp;#39;, length: 256 }, true, [&amp;#39;sign&amp;#39;, &amp;#39;verify&amp;#39;]); console.log(&amp;#39;key =&amp;#39;, key); const enc = new TextEncoder(); const message = enc.encode(&amp;#39;I love cupcakes&amp;#39;); console.log(&amp;#39;message =&amp;#39;, message); const digest = await subtle.sign({ name: &amp;#39;HMAC&amp;#39; }, key, message); console.log(&amp;#39;digest =&amp;#39;, digest); })();</pre> 最初に HMAC キーを生成し、生成されたキーを使用してメッセージ データの整合性と信頼性を検証できます;

次に、文字列

に対して、カップケーキが大好きです

暗号化; 最後に、暗号化されたハッシュ関数であるメッセージ ダイジェストを作成します;

コンソールに表示: キー、メッセージ、ダイジェスト情報

% node server
key = CryptoKey {
  type: &#39;secret&#39;,
  extractable: true,
  algorithm: { name: &#39;HMAC&#39;, length: 256, hash: [Object] },
  usages: [ &#39;sign&#39;, &#39;verify&#39; ]
}
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 解像度調整

Node.js は削除されました

--experimental-specifier-resolution

で、その機能はカスタム ローダーを通じて実現できるようになりました。 このライブラリでテストできます:

nodejs/loaders-test: Node.js ECMAScript モジュール ローダー API をデモンストレーションする例

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

ファイル: <pre class="brush:js;toolbar:false;">import { version } from &amp;#39;process&amp;#39;; import { valueInFile } from &amp;#39;./file&amp;#39;; import { valueInFolderIndex } from &amp;#39;./folder&amp;#39;; console.log(valueInFile); console.log(valueInFolderIndex);</pre>

./file

カスタム ローダーがない場合、ファイルは./file.js./file.mjsカスタム ローダーを設定すると、上記の問題は解決できます。

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

テスト コマンド:

% 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 を使用している人はほとんどおらず、それらを維持することにあまり意味がないことを示しています。

使用を再開したい場合は、問題を報告できます =>

github.com/nodejs/node…

5. V8 エンジンを次のようにアップグレードします。 10.7

Node.js v19 は、V8 JavaScript エンジンを V8 10.7 に更新します。これには、機密数値を書式設定するための新しい関数 Intl.NumberFormat が含まれています。

Intl.NumberFormat(locales, options)

異なる言語の場合は、異なるロケールを渡します:

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. ノード監視モードを試してみる

実行時にノードを追加 -- 監視オプション。

在 "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 教程

以上がNode.js 19 が正式リリースされました。その 6 つの主要な機能についてお話しましょう。の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はjuejin.cnで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。