前几天,Node.js v18
作为当前的稳定版本发布了。我们归纳了 v18 的一些更新。
全局 fetch
Node.js在——试验性-fetch
后有了一个全局fetch
,它允许你在Node.js
中原生使用浏览器fetch
API。在v18中,实验性的Fetch API
默认是可用的。
fetch('https://example.com/todos/1') .then(response => response.json()) .then(json => console.log(json))
你还可以访问FormData、header、Request和Response
对象。
访问Web流媒体API
Node.js现在对Web流媒体API提供了实验性支持:
fetch('https://example.com/api/articles?per_page=1000&page=1') .then(response => response.body) .then(rb => rb.getReader()) .then(reader => { const stream = new ReadableStream({ ... }) })
内置测试框架
node .js现在有一个内置的测试框架,可以在import('node:test')
访问:
import test from 'node:test'; import assert from 'node:assert'; test('true is not false', async t => { assert.strictEqual(true, !false); });
测试:
$ node test.js (node:83584) ExperimentalWarning: The test runner is an experimental feature. This feature could change at any time (Use `node --trace-warnings ...` to show where the warning was created) TAP version 13 ok 1 - true is not false --- duration_ms: 0.000730654 ... 1..1 # tests 1 # pass 1 # fail 0 # skipped 0 # todo 0 # duration_ms 0.074570679
输出为TAP
格式。你可以使用tap
或faucet CLIs
来打印它:
$ npm i -g tap $ tap test.js index.js 2> (node:84725) ExperimentalWarning: The test runner is an experimental feature. This feature could change at any time index.js 2> (Use `node --trace-warnings ...` to show where the warning was created) PASS index.js 1 OK 239.361ms 🌈 SUMMARY RESULTS 🌈 Suites: 1 passed, 1 of 1 completed Asserts: 1 passed, of 1 Time: 415.463ms ----------|---------|----------|---------|---------|------------------- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s ----------|---------|----------|---------|---------|------------------- All files | 0 | 0 | 0 | 0 | ----------|---------|----------|---------|---------|-------------------
- faucet:
$ npm i -g faucet $ node test.js | faucet (node:84914) ExperimentalWarning: The test runner is an experimental feature. This feature could change at any time (Use `node --trace-warnings ...` to show where the warning was created) ✓ true is not false # tests 1 # pass 1 ✓ skipped 0 ✓ todo 0 ✓ duration_ms 0.076367098
二进制文件
用户现在可以使用自定义V8启动快照来构建Node.js
,以提高性能。
通俗地说,这意味着你可以在node.js
源代码中缓存一些依赖项,以提高启动时间。
$ cd /where/is/node/source/code $ ./configure --node-snapshot-main=marked.js # where marked.js is the source of the marked library $ make node
// your-program.js // globalThis.marked is now deserialized from the snapshot // so node.js doesnt need to parse it again // which improves startup time const marked = globalThis.marked; marked(/* ... */);
$ out/Release/node your-program.js
Node.js
正在为此开发JS api
,这意味着我们基本上可以将Node.js应用构建为可分发的二进制文件!
Node.js v18有一些真正令人兴奋的新特性。我一直在等待fetch API
,我一直希望Node.js有二进制文件
。测试框架也很简洁!