>  기사  >  웹 프론트엔드  >  Node.js 19가 공식적으로 출시되었습니다. Node.js의 6가지 주요 기능에 대해 이야기해 보겠습니다!

Node.js 19가 공식적으로 출시되었습니다. Node.js의 6가지 주요 기능에 대해 이야기해 보겠습니다!

青灯夜游
青灯夜游앞으로
2022-11-16 20:34:481460검색

Node 19가 정식 출시되었습니다. 이 글에서는 Node.js 19의 6가지 주요 기능에 대해 자세히 설명하겠습니다. 모든 분들께 도움이 되길 바랍니다! ㅋㅋㅋ Node.js 16(LTS)은 2023년 4월 업데이트 점검이 예정되어 있으며, 2023년 9월 업데이트 점검이 종료될 예정입니다.

그리고 Node 19는 2022-10-18에 출시되었습니다. [관련 튜토리얼 추천: Node.js 19가 공식적으로 출시되었습니다. Node.js의 6가지 주요 기능에 대해 이야기해 보겠습니다!nodejs 동영상 튜토리얼

]

Node.js에는 LTS와 Current


두 가지 버전이 있다는 것을 알고 있습니다. 그 중 Current 버전은 보통 6개월마다 출시됩니다.

매년 4월에 새로운 짝수 버전이 출시됩니다.

매년 10월에 새로운 홀수 버전이 출시됩니다.

지난 10월에 출시된 V19.0.1이 최신 "현재" 얼리 어답터 버전이 되었습니다. 6가지 뛰어난 기능 중.

1. HTTP(S)/1.1 KeepAlive의 기본값은 true입니다.Node.js 19가 공식적으로 출시되었습니다. Node.js의 6가지 주요 기능에 대해 이야기해 보겠습니다!

Node.js v19는 keepAlive 기본값을 true로 설정합니다. 이는 모든 아웃바운드 HTTP(s) 연결이 5S의 기본 시간인 HTTP 1.1 keepAlive를 사용함을 의미합니다. ;

코드 테스트:

const http = require('node:http');
console.log(http.globalAgent);
const https = require('node:https');
console.log(https.globalAgent);

v16과 v19 사이의 노드 서버 에이전트 구성 차이점을 비교할 수 있습니다.

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로 설정됩니다.
% 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를 활성화하면 연결을 재사용하고 네트워크 처리량을 향상시킬 수 있습니다.

또한 서버는 http(s).Server.close API를 사용하여 내부적으로 구현되는 close()를 호출할 때 유휴 클라이언트의 연결을 자동으로 끊습니다.

이러한 수정으로 인해 경험과 성능이 더욱 최적화되었습니다.

  • 2. 안정적인 WebCrypto API

WebCrypto API는 암호화를 사용하여 구축된 시스템 인터페이스로 node.js v19에서 안정적인 경향이 있습니다(Ed25519, Ed448, X25519 제외). X448 제외).

    globalThis.crypto 또는 require('node:crypto').webcrypto를 호출하여 액세스할 수 있습니다. 다음은 미묘한 암호화입니다. 함수: 예
  • 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 문자열을 암호화합니다.

마지막으로 메시지 다이제스트를 만듭니다.

콘솔에 표시: 키, 메시지, 다이제스트 정보close() 自动断开空闲的客户端,内部依靠 http(s).Server.close API 实现;

这些修改,进一步优化了体验和性能。

2. 稳定的 WebCrypto API

WebCrypto API 是一个使用密码学构建的系统接口,在 node.js v19 趋于稳定(除 Ed25519、Ed448、X25519、X448 外)。

我们可以通过调用 globalThis.cryptorequire('node:crypto').webcrypto 来访问,下面以 subtle 加密函数为例;

% 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
}

首先生成 HMAC 密钥,生成的密钥可同时用于验证消息数据完整性和真实性;

然后,对字符串 I love cupcakes 加密;

最后创建 消息摘要,它是一种加密散列函数;

在控制台显示:key 、message 、digest 信息

git clone https://github.com/nodejs/loaders-test.git

% cd loaders-test/commonjs-extension-resolution-loader

% yarn install

3. 自定义 ESM resolution 调整

Node.js 已经删除 --experimental-specifier-resolution ,其功能现在可以通过自定义加载器实现。

可以在这个库中测试:nodejs/loaders-test: Examples demonstrating the Node.js ECMAScript Modules Loaders API

import { version } from &#39;process&#39;;

import { valueInFile } from &#39;./file&#39;;
import { valueInFolderIndex } from &#39;./folder&#39;;

console.log(valueInFile);
console.log(valueInFolderIndex);

比如 loaders-test/commonjs-extension-resolution-loader/test/basic-fixtures/index.js 文件:

import { isBuiltin } from &#39;node:module&#39;;
import { dirname } from &#39;node:path&#39;;
import { cwd } from &#39;node:process&#39;;
import { fileURLToPath, pathToFileURL } from &#39;node:url&#39;;
import { promisify } from &#39;node:util&#39;;

import resolveCallback from &#39;resolve/async.js&#39;;

const resolveAsync = promisify(resolveCallback);

const baseURL = pathToFileURL(cwd() + &#39;/&#39;).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(&#39;file://&#39;)) {
    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&#39;t search for .mjs extensions
      // but it does search for index.mjs files within directories
      extensions: [&#39;.js&#39;, &#39;.json&#39;, &#39;.node&#39;, &#39;.mjs&#39;],
    });
    url = pathToFileURL(resolution).href;
  } catch (error) {
    if (error.code === &#39;MODULE_NOT_FOUND&#39;) {
      // Match Node&#39;s error code
      error.code = &#39;ERR_MODULE_NOT_FOUND&#39;;
    }
    throw error;
  }

  return next(url, context);
}

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

% 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

3. ESM 해상도 조정 사용자 정의

Node.js가 제거되었습니다. --experimental-specifier-solution 및 해당 기능은 이제 사용자 정의 로더를 통해 사용할 수 있습니다.

이 라이브러리에서 테스트할 수 있습니다: nodejs/loaders-test: Node.js ECMAScript 모듈 로더 API

Intl.NumberFormat(locales, options)
를 보여주는 예(예: loaders-test/commonjs-extension-solution-) loader /test/basic-fixtures/index.js 파일:
const number = 123456.789;

console.log(new Intl.NumberFormat(&#39;de-DE&#39;, { style: &#39;currency&#39;, currency: &#39;EUR&#39; }).format(number));
console.log(new Intl.NumberFormat(&#39;ja-JP&#39;, { style: &#39;currency&#39;, currency: &#39;JPY&#39; }).format(number));
console.log(new Intl.NumberFormat(&#39;ar-SA&#39;, { style: &#39;currency&#39;, currency: &#39;EGP&#39; }).format(number));
console.log(new Intl.NumberFormat(&#39;zh-CN&#39;, { style: &#39;currency&#39;, currency: &#39;CNY&#39; }).format(number));

./file 사용자 정의 로더가 없으면 와 같은 파일 확장자가 검색되지 않습니다. . /file.js 또는 ./file.mjs

사용자 정의 로더를 설정한 후 위의 문제를 해결할 수 있습니다:

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
오류가 발생합니다. 더 이상 보고되지 않으며 정상적으로 작동됩니다.

4. DTrace/SystemTap/ETW에 대한 지원이 제거되었습니다.

Node.js v19에서는 주로 리소스 우선순위 문제로 인해 DTrace/SystemTap/ETW에 대한 지원이 제거되었습니다.

데이터에 따르면 DTrace, SystemTap 또는 ETW를 사용하는 사람은 거의 없으며 이를 유지하는 데 큰 의미가 없습니다.

사용을 재개하려면 문제를 제기할 수 있습니다 =>

github.com/nodejs/node… 10.7에는 민감한 숫자의 형식을 지정하기 위한 새로운 함수 Intl.NumberFormat이 포함되어 있습니다. rrreee다른 언어의 경우 다른 로케일을 전달하세요.

rrreee

6. Node 감시 모드 실험🎜🎜🎜실행 시 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相关知识,请访问:nodejs 教程

위 내용은 Node.js 19가 공식적으로 출시되었습니다. Node.js의 6가지 주요 기능에 대해 이야기해 보겠습니다!의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 juejin.cn에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제