您好,登錄后才能下訂單哦!
今天小編給大家分享一下Node.js19有哪些特性的相關(guān)知識(shí)點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識(shí),所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來(lái)了解一下吧。
Node.js 14 將在 2023 年 4 月結(jié)束更新維護(hù),Node.js 16 (LTS) 預(yù)計(jì)將在 2023 年 9 月結(jié)束更新維護(hù)。
而Node 19 在 2022-10-18 發(fā)布。
我們知道 Node.js 版本分兩種:LTS 和 Current
其中,Current 版本通常每 6 個(gè)月發(fā)布一次。
每年 4 月份發(fā)布新的偶數(shù)版本;
每年 10 月份發(fā)布新的奇數(shù)版本;
在剛過去的 10 月,發(fā)布的 V19.0.1 成為最新的 “Current” 嘗鮮版,它一共帶來(lái) 6 大特性。
Node.js v19 設(shè)置 keepAlive 默認(rèn)值為 true,這意味著所有出站的 HTTP(s) 連接都將使用 HTTP 1.1 keepAlive,默認(rèn)時(shí)間為 5S;
代碼測(cè)試:
我們可以對(duì)比看看 v16 和 v19 的 node server Agent 配置差異:const http = require('node:http');
console.log(http.globalAgent);
const https = require('node:https');
console.log(https.globalAgent);
V16
第 18、40 行,keepAlive 默認(rèn)設(shè)置為 false;% 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
}
V19
第 14、16、42、44 行設(shè)置 keepAlive 默認(rèn)值及時(shí)間;% 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
}
啟用 keepAlive 能使連接重用,提高網(wǎng)絡(luò)的吞吐量。
另外,服務(wù)器將在調(diào)用 close()
自動(dòng)斷開空閑的客戶端,內(nèi)部依靠 http(s).Server.close
API 實(shí)現(xiàn);
這些修改,進(jìn)一步優(yōu)化了體驗(yàn)和性能。
WebCrypto API 是一個(gè)使用密碼學(xué)構(gòu)建的系統(tǒng)接口,在 node.js v19 趨于穩(wěn)定(除 Ed25519、Ed448、X25519、X448 外)。
我們可以通過調(diào)用 globalThis.crypto
或 require('node:crypto').webcrypto
來(lái)訪問,下面以 subtle
加密函數(shù)為例;
首先生成 HMAC 密鑰,生成的密鑰可同時(shí)用于驗(yàn)證消息數(shù)據(jù)完整性和真實(shí)性;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);
})();
然后,對(duì)字符串 I love cupcakes
加密;
最后創(chuàng)建 消息摘要,它是一種加密散列函數(shù);
在控制臺(tái)顯示: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
}
Node.js 已經(jīng)刪除 --experimental-specifier-resolution
,其功能現(xiàn)在可以通過自定義加載器實(shí)現(xiàn)。
可以在這個(gè)庫(kù)中測(cè)試: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 'process';
import { valueInFile } from './file';
import { valueInFolderIndex } from './folder';
console.log(valueInFile);
console.log(valueInFolderIndex);
./file
如果沒有自定義加載器,不會(huì)去查找文件的擴(kuò)展名,比如 ./file.js
或 ./file.mjs
設(shè)置自定義加載器后,則可解決上述問題:
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);
}
測(cè)試命令:
% 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
將不會(huì)再報(bào)錯(cuò),正常運(yùn)行。
在 Node.js v19中,移除了對(duì) DTrace/SystemTap/ETW 的支持,主要是因?yàn)橘Y源的優(yōu)先級(jí)問題。
數(shù)據(jù)表明很少人用到 DTrace、SystemTap 或 ETW,維護(hù)它們沒有多大的意義。
如果你想恢復(fù)使用,可提 issues => github.com/nodejs/node…
Node.js v19 將 V8 JavaScript 引擎更新至 V8 10.7,其中包含一個(gè)新函數(shù) Intl.NumberFormat,用于格式化敏感數(shù)字。
Intl.NumberFormat(locales, options)
對(duì)于不同的語(yǔ)言,傳入不同的 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));
運(yùn)行時(shí)增加了 node --watch 選項(xiàng)。
在 "watch" 模式下運(yùn)行,當(dāng)導(dǎo)入的文件被改變時(shí),會(huì)重新啟動(dòng)進(jìn)程。
比如:
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.js19有哪些特性”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會(huì)為大家更新不同的知識(shí),如果還想學(xué)習(xí)更多的知識(shí),請(qǐng)關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。