Node.js v12.17.0 (LTS) 发布

Node.js v12.17.0 (LTS) 已发布,更新内容包括移除 ECMAScript 模块--experimental-modulesflag、引入 AsyncLocalStorage API(实验性阶段)、文件系统 API、改进对 REPL 的预览等内容。

移除 ECMAScript 模块的--experimental-modulesflag

从 Node.js 12.17.0 开始,使用 ECMAScript 模块(ESM)不再需要--experimental-modulesflag。不过 Node.js 中的 ESM 实现仍处于实验性阶段,建议使用者在生产环境谨慎使用此功能。

与 Node.js 14 不同,在 Node.js v12.17.0 中无论是在应用程序的入口端点使用模块时,还是第一次调用动态 import() 时,使用 ESM 仍会触发 runtime 实验性警告。

团队表示预计在今年晚些时候,可能在10月下旬,也就是 Node.js 14 成为 LTS 的时候,会移除 Node.js 12 中的警告。

引入 AsyncLocalStorage API (experimental)

Async Hooks 模块已引入 AsyncLocalStorage 类。

此 API 这次在异步操作中保存一个上下文。例如,如果在 AsyncLocalStorage 的一个实例中存储了一个序列id,对于每一个进入服务器的 HTTP 请求,就可以在不访问当前 HTTP 请求的情况下检索这个 id。

const http = require('http');
const { AsyncLocalStorage } = require('async_hooks');

const asyncLocalStorage = new AsyncLocalStorage();

function logWithId(msg) {
  const id = asyncLocalStorage.getStore();
  console.log(`${id !== undefined ? id : '-'}: `, msg);
}

let idSeq = 0;
http.createServer((req, res) => {
  asyncLocalStorage.run(idSeq++, () => {
    logWithId('start');
    // Imagine any chain of async operations here.
    setImmediate(() => {
      logWithId('finish');
      res.end();
    });
  });
}).listen(8080);

在上面的例子中,logWithId 函数始终都知道当前的请求 id 是什么,即使有多个请求并行时也是如此。

此 API 的使用案例包括:

  • 日志
  • 用户认证
  • 性能追踪
  • 错误追踪和处理等
  • ……

注意:此 API 仍处于实验性阶段,有些方法可能会在未来的 Node.js 版本中发生变化。

扫描二维码关注公众号,回复: 11281147 查看本文章

文件系统(File system APIs)

新函数:fs.readv

此新函数(以及它的 sync 和 promisified 版本)会取一个数组的ArrayBufferView元素,并将其读取的数据按顺序写入缓冲区。

fs.read的可选参数

fs.read有了一个新的重载(以及它的 sync 和 promisified 版本),允许选择性地传递任何偏移、长度和位置(offsetlengthposition )参数。

详情查看:https://nodejs.org/en/blog/release/v12.17.0/
下载地址:https://nodejs.org/en/download/

猜你喜欢

转载自www.oschina.net/news/115984/nodejs-12-17-0-lts