JavaScript/Node

Node.js v15.0.0 릴리즈 소식

kjmin 2020. 10. 27. 15:27
본 글은 nodejs.medium.com/node-js-v15-0-0-is-here-deb00750f278의 내용을 기반으로 작성되었습니다.
본 글의 내용은 원문의 내용에 대한 보완 설명과 예제 코드를 포함하고 있습니다. 코드는 [JavaScript MDN]에서 제공하는 예제를 참고하여 작성했습니다.

2020.10.20에 Node.js의 새로운 버전인 v15.0.0이 릴리즈 되면서 LTS Release와 Current Release의 버전이 교체됩니다.

LTS Release: 12 -> 14

Current Release: 14 -> 15

그간 Release 규칙에 따르면, LTS Release는 짝수 단위로 교체되어 왔습니다. 따라서 다음 버전의 Current Release(v16)가 출시되어도 LTS Release는 v15로 교체되지 않습니다.

v15.0.0의 핵심은 다음과 같습니다.

 

1. AbortController (Experimental Implementation)

관련 문서 [nodejs.org/docs/latest-v15.x/api/globals.html#globals_class_abortcontroller]

AbortController의 API 명세에 따라서 전역 유틸리티 클래스로 구현되었으며, Promise API 호출에서 취소 시그널을 보내는 역할을 수행합니다. (글로벌 스페이스에 할당되어 있으므로 별도의 모듈 require을 요구하지 않음)

const ac = new AbortController();
ac.signal.addEventListener('abort', () => console.log('Aborted!'),
{ once: true });
ac.abort();
console.log(ac.signal.aborted);  // Prints True

위의 코드처럼 AbortController의 인스턴스에서 abort() 함수를 호출하면, 해당 인스턴스에서 abort 이벤트가 트리거됩니다.

AbortController은 단 한번만 트리거되어야 합니다. 따라서 이벤트 리스너를 등록할 때 { once: true } 옵션을 주어 이벤트 핸들링을 마치면 리스너가 제거되도록 해야 합니다. (위 동작은 Event Emitter의 once API 에 해당함. [관련 문서])

 

2. N-API v7

이번 버전의 N-API는 ArrayBuffers 작업을 위한 추가 메소드를 제공합니다.

3. NPM v7

관련 문서 [github.blog/2020-10-13-presenting-v7-0-0-of-the-npm-cli]

v15부터 새로운 NPM v7버전이 제공됩니다.

v7에서는 npm workspace, 새로운 package-lock.json 포맷, yarn.lock 파일에 대한 지원 등이 추가됩니다.

4. unhandled rejection에 대한 Throw (원문:Throw on unhandled rejections)

그림 1.Unhandled Rejection with Warn

그동안의 릴리즈에서, Node.js는 Promise 호출 시 reject에 대한 처리가 없을 경우 그림 1처럼 경고를 출력했습니다.

그러나, Unhandled Rejection에 대한 유저 설문을 통해 Warn 대신 Exception을 Throw하는 것이 더 올바른 동작이라는 결론을 내렸고, v15부터 이를 반영했습니다.

그림 2.Unhandled Rejection with Throw

따라서, Node.js v15 부터는 단순한 경고 출력 대신 그림 2와 같이 Exception을 throw합니다.

프로세스 실행 옵션에서 --unhandled-rejections=warn 또는 --unhandled-rejections=throw을 통해 unhandled rejection에 대한 동작을 변경할 수 있습니다.

5. QUIC (Experimental)

관련 문서 [https://nodejs.org/dist/latest-v15.x/docs/api/quic.html]

HTTP/3 의 기본 프로토콜인 QUIC 프로토콜에 대한 실험적 지원이 추가됩니다. --experimental-quic 플래그를 통해 활성화가 가능하며, 빌트인 모듈인 net 에서 QUIC 구현에 대한 API를 제공합니다.

const { createQuicSocket } = require(‘net’);

6. V8 v8.6

V8의 버전이 8.6으로 업데이트 되었습니다. (최신 버전의 v14 릴리즈에서는 v8.4가 적용되어 있음)

V8의 업데이트에 따라서 다음과 같은 추가 기능을 이용할 수 있습니다.

a. Promise.any() [developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/any]

Promise.any()는 Promise 배열을 파라미터로 전달받으며, 전달받은 Promise를 순회하여 가장 먼저 resolve된 Promise만을 반환합니다.(즉, resolve된 모든 Promise의 value를 반환하는 Promise.any()[관련 문서]와 반대되는 동작을 수행함)

만약 모든 Promise가 resolve되지 않는다면(즉, 모든 Promise가 reject를 반환하면), 하단에 서술할 AggregateError을 반환합니다.

const promise1 = Promise.reject(0);
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'quick'));
const promise3 = new Promise((resolve) => setTimeout(resolve, 500, 'slow'));

const promises = [promise1, promise2, promise3];

Promise.any(promises).then((value) => console.log(value)).catch(() => {});
// expected output: "quick"

 

b. AggregateError [developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError]

AggregateError은 다수의 오류를 단일 오류로 래핑해야 할 때 사용됩니다. 이 에러가 사용되는 예가 상단의 Promise.any() 입니다.

Promise.any()는 실행한 모든 Promise가 reject되었을 경우, 모든 reject에 대한 오류를 한 번에 반환해야 하기 때문에 AggregateError을 사용합니다,

Promise.any([
    Promise.reject(new Error("Hello, Error!")),
    Promise.reject(new Error("Rejected Promise")),
]).catch(e => {
  console.log(e instanceof AggregateError); // true
  console.log(e.message);                   // "All Promises rejected"
  console.log(e.name);                      // "AggregateError"
  console.log(e.errors);                    // [ Error: "Hello, Error!", Error: "Rejected Promise" ]
});

c. String.prototype.replaceAll() [developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll]

기존의 String.prototype.replace() 메소드는 문자열 내에서 하나의 문자에 대한 치환밖에 할 수 없다. replaceAll() 메소드는 패턴과 매칭되는 모든 문자를 치환하는 기능을 제공합니다.

const text = '나는..가끔..눈물을..흘린다..'
const _replace = text.replace(".", "!")
const _replaceAll = text.replaceAll(".", "!")
console.log(text) 		// Prints "나는..가끔..눈물을..흘린다.."
console.log(_replace) 		// Prints "나는!.가끔..눈물을..흘린다.."
console.log(_replaceAll)	// Prints "나는!!가끔!!눈물을!!흘린다!!"

d. Logical assignment operator (&&=, ||=, ??=) [developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators]

Logical And Assignment (&&=)는 좌측 피연산자가 truthy 값일 경우에만 값 할당을 수행합니다.

let truthy = "Hello"
let falsy = 0
truthy &&= "World"
falsy &&= "World"
console.log(truthy) // Prints "World"
console.log(falsy)  // Prints 0

Logical Or Assignment (||=)는 좌측 피연산자가 falsy 값일 경우에만 값 할당을 수행합니다.

let truthy = "Hello"
let falsy = 0
truthy ||= "World"
falsy ||= "World"
console.log(truthy) // Prints "Hello"
console.log(falsy)  // Prints "World"

Logical Nullish Assignment (??=)는 좌측 피연산자가 null 또는 undefined일 경우에만 값 할당을 수행합니다.

const a = { duration: 50 };
a.duration ??= 10;
console.log(a.duration); // Prints 50
a.speed ??= 25;
console.log(a.speed);    // Prints 25

 

* nullish와 falsy 차이점

falsy는 null과 undefined를 포함하여 NaN, 0, "" 등 JavaScript에서 eval 시 false로 평가되는 모든 값을 의미합니다.

반면 nullish는 null과 undefined만 해당합니다. 즉, nullish는 항상 falsy 값이지만 그 역은 성립하지 않는 관계

 

 

'JavaScript > Node' 카테고리의 다른 글

(소개) keymetrics.io  (0) 2016.12.28