目錄
2. 穩定的WebCrypto API
#3. 自訂ESM resolution 調整
4. 移除對DTrace/SystemTap/ETW 支援
5. 升級V8 引擎至10.7
#6. 試驗Node watch 模式
首頁 web前端 js教程 Node.js 19正式發布,聊聊它的 6 大功能!

Node.js 19正式發布,聊聊它的 6 大功能!

Nov 16, 2022 pm 08:34 PM
javascript 前端 node.js

Node 19已正式發布,以下這篇文章就來帶大家詳解了解Node.js 19的 6 大特性,希望對大家有幫助!

Node.js 19正式發布,聊聊它的 6 大功能!

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


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

而Node 19 在 2022-10-18 發布。 【相關教學推薦:nodejs影片教學

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

Node.js 19正式發布,聊聊它的 6 大功能!

##其中,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 ,其功能現在可以透過自訂載入器實作。

可以在這個函式庫中測試:

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

例如

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

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 如果沒有自訂載入器,就不會去找文件的副檔名,例如./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,維護它們沒有多大的意義。

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

github.com/nodejs/node…

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(&#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. 試驗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相关知识,请访问:nodejs 教程

以上是Node.js 19正式發布,聊聊它的 6 大功能!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

PHP與Vue:完美搭檔的前端開發利器 PHP與Vue:完美搭檔的前端開發利器 Mar 16, 2024 pm 12:09 PM

PHP與Vue:完美搭檔的前端開發利器在當今網路快速發展的時代,前端開發變得愈發重要。隨著使用者對網站和應用的體驗要求越來越高,前端開發人員需要使用更有效率和靈活的工具來創建響應式和互動式的介面。 PHP和Vue.js作為前端開發領域的兩個重要技術,搭配起來可以稱得上是完美的利器。本文將探討PHP和Vue的結合,以及詳細的程式碼範例,幫助讀者更好地理解和應用這兩

前端面試官常問的問題 前端面試官常問的問題 Mar 19, 2024 pm 02:24 PM

在前端開發面試中,常見問題涵蓋廣泛,包括HTML/CSS基礎、JavaScript基礎、框架和函式庫、專案經驗、演算法和資料結構、效能最佳化、跨域請求、前端工程化、設計模式以及新技術和趨勢。面試官的問題旨在評估候選人的技術技能、專案經驗以及對行業趨勢的理解。因此,應試者應充分準備這些方面,以展現自己的能力和專業知識。

簡易JavaScript教學:取得HTTP狀態碼的方法 簡易JavaScript教學:取得HTTP狀態碼的方法 Jan 05, 2024 pm 06:08 PM

JavaScript教學:如何取得HTTP狀態碼,需要具體程式碼範例前言:在Web開發中,經常會涉及到與伺服器進行資料互動的場景。在與伺服器進行通訊時,我們經常需要取得傳回的HTTP狀態碼來判斷操作是否成功,並根據不同的狀態碼來進行對應的處理。本篇文章將教你如何使用JavaScript來取得HTTP狀態碼,並提供一些實用的程式碼範例。使用XMLHttpRequest

Django是前端還是後端?一探究竟! Django是前端還是後端?一探究竟! Jan 19, 2024 am 08:37 AM

Django是一個由Python編寫的web應用框架,它強調快速開發和乾淨方法。儘管Django是web框架,但要回答Django是前端還是後端這個問題,需要深入理解前後端的概念。前端是指使用者直接和互動的介面,後端是指伺服器端的程序,他們透過HTTP協定進行資料的互動。在前端和後端分離的情況下,前後端程式可以獨立開發,分別實現業務邏輯和互動效果,資料的交

Go語言前端技術探秘:前端開發新視野 Go語言前端技術探秘:前端開發新視野 Mar 28, 2024 pm 01:06 PM

Go語言作為一種快速、高效的程式語言,在後端開發領域廣受歡迎。然而,很少有人將Go語言與前端開發聯繫起來。事實上,使用Go語言進行前端開發不僅可以提高效率,還能為開發者帶來全新的視野。本文將探討使用Go語言進行前端開發的可能性,並提供具體的程式碼範例,幫助讀者更了解這一領域。在傳統的前端開發中,通常會使用JavaScript、HTML和CSS來建立使用者介面

Golang與前端技術結合:探討Golang如何在前端領域發揮作用 Golang與前端技術結合:探討Golang如何在前端領域發揮作用 Mar 19, 2024 pm 06:15 PM

Golang與前端技術結合:探討Golang如何在前端領域發揮作用,需要具體程式碼範例隨著互聯網和行動應用的快速發展,前端技術也愈發重要。而在這個領域中,Golang作為一門強大的後端程式語言,也可以發揮重要作用。本文將探討Golang如何與前端技術結合,以及透過具體的程式碼範例來展示其在前端領域的潛力。 Golang在前端領域的角色作為一門高效、簡潔且易於學習的

如何在JavaScript中取得HTTP狀態碼的簡單方法 如何在JavaScript中取得HTTP狀態碼的簡單方法 Jan 05, 2024 pm 01:37 PM

JavaScript中的HTTP狀態碼取得方法簡介:在進行前端開發中,我們常常需要處理與後端介面的交互,而HTTP狀態碼就是其中非常重要的一部分。了解並取得HTTP狀態碼有助於我們更好地處理介面傳回的資料。本文將介紹使用JavaScript取得HTTP狀態碼的方法,並提供具體程式碼範例。一、什麼是HTTP狀態碼HTTP狀態碼是指當瀏覽器向伺服器發起請求時,服務

Django:前端和後端開發都能搞定的神奇框架! Django:前端和後端開發都能搞定的神奇框架! Jan 19, 2024 am 08:52 AM

Django:前端和後端開發都能搞定的神奇框架! Django是一個高效、可擴展的網路應用程式框架。它能夠支援多種Web開發模式,包括MVC和MTV,可以輕鬆地開發出高品質的Web應用程式。 Django不僅支援後端開發,還能夠快速建構出前端的介面,透過模板語言,實現靈活的視圖展示。 Django把前端開發和後端開發融合成了一種無縫的整合,讓開發人員不必專門學習

See all articles