NodeJS 18 来了!2个让你大吃一惊的功能!

242 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情

1_7mTnKPO0SqPLhGn5XFWjOg.png

NodeJS发布了新版本,名为NodeJS 18,它为开发者提供了许多新功能供他们使用,这些新功能可以帮助开发者提高生产力提高性能,本文将带领您讨论这些重要的新功能。

NodeJS 18已将V8 JavaScript引擎更新到10.1版本,该版本来自 Chromium 101。由于该更新,引入findLast()findLastIndex()等方法, Intl.supportedValuesOf 函数、Intl.LocaleAPI改进以及类字段和私有类方法的更好性能!

截屏2022-10-08 上午10.08.14.png

独立测试运行器

测试在我们项目中至关重要,它是管理我们项目在生产中正常运行的至关重要的环节。

通常在NodeJS中编写单元测试常用的框架有以下几种:JESTMochaJSAVASuperTest等。但是现在从18版本开始,NodeJS有了原生方法来实现测试,使用这个原生API的方式如下:

import test from 'node:test';
import assert from 'node:assert';
test('synchronous passing test', (t) => {
  // This test passes because it does not throw an exception.
  assert.strictEqual(1, 1);
});

test('synchronous failing test', (t) => {
  // This test fails because it throws an exception.
  assert.strictEqual(1, 2);
});

也可以使用test()函数的上下文来创建子测试,比如这个:

import test from 'node:test';
import assert from 'node:assert';

test('top level test', async (t) => {
  await t.test('subtest 1', (t) => {
    assert.strictEqual(1, 1);
  });

  await t.test('subtest 2', (t) => {
    assert.strictEqual(2, 2);
  });
});

这里需要注意❗️:在导入test必须添加node:前缀

在 NodeJS 18 以后,新增的内置库只有添加 node: 前缀这一种书写方式。当然,为了向前兼容的需要。原有核心模块的引入方式还是两种模式都支持。

Fetch API

这是NodeJS社区最受欢迎的功能了,因为我们终于可以在NodeJS上下文环境中使用该fetch功能了。Node.js 18 内置了 fetch 模块,fetch API 可全局调用,无需引入 node-fetch 包。众所周知,JavaScript可以直接在浏览器中运行,在这种情况下,使用函数发出fetch请求是最方便自然的。例如向某些API发出请求,如下:

function getProducts(){
    fetch('https://api.site.com/api/v1/products')
    .then(response => response.json())
    .then(data => console.log(data))
}

使用上面的代码你可以发出请求并且得到返回结果,同时,你也可以使用async/await来实现它,比如这个例子:

async function getProducts(){
    const response = await fetch('https://api.site.com/api/v1/products');
    const data = await response.json();
    console.log(data);
}

假如在服务端,我们也想发出fetch请求,或连接到其他服务呢?在现在的NodeJS 18版本中,正在致力于实验性支持,以便fetch可以执行,让我们看一个NodeJS 的例子:

const res = await fetch('https://api.site.com/api/v1/products')
if(res.OK){
    const data = await res.json();
    console.log(data)
}

所以,现在我们可以在浏览器中使用fetch发出请求了。

总结

更多NodeJS 18的内容可以 参考文档学习哦!