Node.js v19,它来了。详解 6 大特性

news2024/10/7 4:37:05

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


Node 19 在 2022-10-18 发布。

我们知道 Node.js 版本分两种:LTS 和 Current

其中,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.crypto 或 require('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 'process';

import { valueInFile } from './file';
import { valueInFolderIndex } from './folder';

console.log(valueInFile);
console.log(valueInFolderIndex);
复制代码

./file 如果没有自定义加载器,不会去查找文件的扩展名,比如 ./file.js 或 ./file.mjs

设置自定义加载器后,则可解决上述问题:

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);
}
复制代码

测试命令:

% 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('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));
复制代码

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.js 19 is now available! | Node.js

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/13999.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

C语言第十课(下):优化井字棋游戏

目录 前言&#xff1a; 一、优手着棋判定&#xff1a; 1.防守型着棋优化&#xff1a; 2.进攻型着棋优化&#xff1a; 二、界面格式优化&#xff1a; 1.Sleep休眠语句&#xff1a; 2.system语句&#xff1a; 三、优化后最终全部代码&#xff1a; 1.头文件game.h: 2.函数功能…

MFIF:Deep Regression Pair Learning

DRPL: Deep Regression Pair Learning for Multi-Focus Image Fusion 本文提出了一种用于多焦点图像融合的新型深度网络&#xff0c;称为深度回归对学习 (DRPL)。与现有的深度融合方法将输入图像分割成小的补丁并应用分类器来判断补丁是否聚焦相比&#xff0c;DRPL直接将整个图…

java springboot获取GitLab上的文件内容

这里以最简单的方式获取git上的文件,并读取文件 第一步:获取主域名host 进入网页版的git,链接为:https://gitlab.***.com 第二步:获取access_token 在git网页端登录后的右上角用户头像下拉菜单的settings页面===>再点击settings页面的左侧菜单栏中的Access Tokens选…

Shell 脚本编程(二) —— 条件判断 (test命令) + 多路分支语句(if 、case)

test 命令可以用于判断文件类型以及值的比较&#xff0c;test 判断条件为真&#xff0c;返回 0&#xff1b;条件为假&#xff0c;返回 1。 目录 一、条件判断 (1) 整数判断 (2) 字符串判断 (3) 文件判断 二、if 语句 1、语法结构 2、实际运用 三、case语句 一、条件判断…

【毕业设计】图像识别跌倒检测算法研究与实现 - python 深度学习 机器学习

文章目录0 前言1 简介2 实现方法2.1 传统机器视觉算法2.2 基于机器学习的跌倒检测2.2.1 SVM简介2.2.2 SVM跌倒检测原理2.2.3 算法流程2.2.4 算法效果2.3 深度学习跌倒检测2.3.1 最终效果2.3.2 网络原理3 最后0 前言 &#x1f525; Hi&#xff0c;大家好&#xff0c;这里是丹成…

Java集合框架【二容器(Collection)[ArrayList]】

文章目录1 容器/集合简介2 容器的结构2.1 结构图2.1.1 单例集合2.1.2 双例集合3 单例集合的使用3.1 Collection接口的介绍3.2 Collection接口中的接口方法3.3 List接口3.3.1 List接口特点3.3.2List的常用方法3.4 ArrayList容器类3.4.1 添加元素3.4.2 获取元素3.4.3 根据索引删除…

水尺监测识别系统

水尺监测识别系统利用计算机视觉机器学习技术对河道湖泊进行实时检测&#xff0c;当水尺监测识别系统监测到河道水位异常时&#xff0c;立即告警。水尺监测识别系统同时将告警截图和视频保存下来&#xff0c;推送给后台。水尺监测识别系统极大提升现场区域的管控效率&#xff0…

android EventBus

EventBus使用小案例 文件目录结构 MainActivity.java package com.example.myeventbus;import androidx.appcompat.app.AppCompatActivity;import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import andro…

两万字长文带你深入Go语言GC源码

介绍 三色标记法 三色标记法将对象的颜色分为了黑、灰、白&#xff0c;三种颜色。 黑色&#xff1a;该对象已经被标记过了&#xff0c;且该对象下的属性也全部都被标记过了&#xff08;程序所需要的对象&#xff09;&#xff1b;灰色&#xff1a;该对象已经被标记过了&#…

一段JS去除畅言免费版广告

畅言广告怎么去掉&#xff1f;去除畅言免费版广告方法是什么&#xff1f;现在很多站长都使用的社会化评论系统&#xff0c;可以让网站拥有免费的评论区&#xff0c;活化你的网站&#xff0c;但是随着很多社会化评论提供网站的关闭&#xff0c;畅言一家独大&#xff0c;现在免费…

企业网络自动化配置

更新的技术、合规性标准和不断变化的业务需求使管理当今的网络成为一项具有挑战性的任务。这解释了网络自动化在当今世界的重要性。IT 管理员现在的任务是确保网络的敏捷性和演进不会影响提供给最终用户的网络服务的稳定性、可用性和可靠性。但是&#xff0c;在此任务中&#x…

【JMX】JMX远程监控JVM参数配置

目录基本用法命令示例jconsole连接新建连接确认连接方式查看监控信息jvisualvm连接添加主机增加JMX连接查看监控信息参数说明基本参数jmxremote.access文件说明jmxremote.password文件说明文件权限异常无法验证基本用法 命令示例 #参考命令 java -Dcom.sun.management.jmxrem…

【Java学习】语法:包、权限修饰符、final、常量、枚举、抽象类、接口

文章目录一、包二、权限修饰符三、final四、常量五、枚举六、抽象类七、接口一、包 什么是包? 包是用来分门别类的管理各种不同类的&#xff0c;类似于文件夹、建包利于程序的管理和维护。建包的语法格式: package公司域名倒写.技术名称。报名建议全部英文小写&#xff0c;且…

WebRTC系列<二> 案例与工具

阅读关于webRTC的其他文章&#xff1a; WebRTC系列&#xff1c;一&#xff1e; 什么是WebRTC&#xff1f; WebRTC系列&#xff1c;二&#xff1e; 案例与工具 ---------------------------------案例--------------------------------- webrtc官网 : 官网示例代码github地址…

【Raspberry Pi】搭建NAS流媒体播放器 + ARIA2 + YAAW + 迅雷下载系统

由于种&#xff08;gu&#xff09;种&#xff08;ji&#xff09;原&#xff08;cuo&#xff09;因&#xff08;wu&#xff09;新买的Pi并没有用于任何项目上&#xff0c;看着它一天一天的封尘&#xff0c;于心不忍终于让它也做了点事。恰好这几天家里网络晚上有点卡&#xff0c…

数字集成电路设计(四、Verilog HDL数字逻辑设计方法)(二)

文章目录3. 时序电路的设计3.1 触发器3.1.1 最简单的D触发器3.1.2 带复位端的D触发器3.1.3 复杂功能的D触发器&#xff08;没有太大必要&#xff09;3.1.4 T触发器3.2 计数器3.2.1 二进制计数器3.2.2 &#xff08;重要&#xff09;任意进制计数器3.3 移位寄存器3.4 序列信号发生…

docker命令整理

第一次安装 查看docker是否安装成功 docker version 测试hello-world docker run hello-world –help 帮助 查看详细信息 docker info 搜索docker镜像网址&#xff1a;https://hub.docker.com/search 查看 查看cpu实时内存 docker stats 镜像关键字&#xff1a;images -…

MySQL-Redis进阶生成全局唯一ID

单体全局ID 场景一、随着我们商城规模越来越大&#xff0c;mysql的单表的容量不宜超过500W&#xff0c;数据量过大之后&#xff0c;我们要进行拆库拆表&#xff0c;但拆分表了之后&#xff0c;他们从逻辑上讲他们是同一张表&#xff0c;所以他们的id是不能一样的&#xff0c; …

阿里最新财报:中国商业分部收入下滑1%,年内股价累计下跌34%

11月17日&#xff0c;阿里巴巴集团&#xff08;下称“阿里巴巴”&#xff0c;HK:09988、NYSE:BABA&#xff09;公布2023财年第二季度&#xff08;对应自然年2022年第三季度&#xff09;业绩。财报显示&#xff0c;阿里巴巴2022年第三季度的收入为人民币2071.76亿元&#xff08;…

[附源码]java毕业设计流浪动物领养系统

项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术&#xff1a; SSM mybatis Maven Vue 等等组成&#xff0c;B/S模式 M…