Node.js 22 introduces exciting new features and improvements. This tutorial will guide you through the key enhancements and how to use them effectively.
Node.js 22 includes improved WebAssembly garbage collection, reducing memory leaks.
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();
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' }
Maglev is enabled by default, enhancing CLI tool startup without configuration.
Use --experimental-require-module
to mix CommonJS and ESM.
Example:
// main.cjs
const myESM = require('./myESM.mjs');
console.log(myESM);
Run package scripts like node --run test
as an npm test alternative.
Use node --watch
for automatic restarts on file changes.
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);
};
Find files with the built-in fs.glob()
method.
Example:
const files = fs.glob('src/**/*.js');
console.log(files);
Default high water mark for streams is now 64 KiB.
node --trace-deprecation
.This concludes the Node.js 22 tutorial. Explore these features to enhance your applications.