Looks like you're stuck. Need a hand?

Share This Tutorial

Views 68

Node.js 22

Date  |  Category Programming
...
...
Back Back

Node.js 22 Tutorial

Node.js 22 introduces exciting new features and improvements. This tutorial will guide you through the key enhancements and how to use them effectively.

1. V8 Engine 12.4 Features

WebAssembly Garbage Collection

Node.js 22 includes improved WebAssembly garbage collection, reducing memory leaks.

Array.fromAsync()

Create arrays from async iterators with Array.fromAsync().

Example:

async function* generateNumbers() {
  for (let i = 0; i < 5; i++) {
    yield i;
  }
}

async function main() {
  const numbers = await Array.fromAsync(generateNumbers());
  console.log(numbers); // [0, 1, 2, 3, 4]
}

main();

Set and Map Helpers

New methods for Set and Map simplify operations.

Grouping and Merging:

const map1 = new Map([[1, 'a'], [2, 'b']]);
const map2 = new Map([[2, 'c'], [3, 'd']]);

const mergedMap = Map合并(map1, map2);
console.log(mergedMap); // Map(3) { 1 => 'a', 2 => 'c', 3 => 'd' }

2. Maglev Compiler

Maglev is enabled by default, enhancing CLI tool startup without configuration.

3. require() for ESM Graphs

Use --experimental-require-module to mix CommonJS and ESM.

Example:

// main.cjs
const myESM = require('./myESM.mjs');
console.log(myESM);

4. Execute Scripts Directly with node --run

Run package scripts like node --run test as an npm test alternative.

5. Watch Mode for Development

Use node --watch for automatic restarts on file changes.

6. Built-in WebSocket Client

Node.js 22 includes a browser-compatible WebSocket client.

Example:

const ws = new WebSocket('ws://localhost:8080');
ws.onmessage = (event) => {
  console.log('Received:', event.data);
};

7. fs.glob() for File Matching

Find files with the built-in fs.glob() method.

Example:

const files = fs.glob('src/**/*.js');
console.log(files);

8. Streams with 64 KiB High Water Mark

Default high water mark for streams is now 64 KiB.

9. Upgrade Guide

This concludes the Node.js 22 tutorial. Explore these features to enhance your applications.