Open Menu

    Node.js 22. The Next Leap Forward

    Flavio Del Grosso

    Flavio Del GrossoApr 26, 2024

    5 min read1114 words

    Welcome to the latest release of Node.js! I'm thrilled to walk you through the exciting updates and enhancements in version 22. Thanks to Marco Ippolito, Rafael Gonzaga, Joyee Cheung and the other contributors for their hard work in making this release possible.

    V8 engine update to version 12.4

    WebAssembly Garbage Collection

    One of the standout features of this release is the upgrade to V8 version 12.4, which brings WebAssembly Garbage Collection enhancemente into play. This advancement improves memory management for WebAssembly code, promising enhanced performance and efficiency for your applications.

    Array Creations From Async Iterables

    Let's talk about Array.fromAsync, a game-changer. This new method empowers you to create arrays asynchronously from async iterables. Here's a glimpse of its power:

    javascript

    // Example of Array.fromAsync
    async function* asyncIterable() {
      for (let i = 0; i < 5; i++) {
        await new Promise((resolve) => setTimeout(resolve, 10 * i));
        yield i;
      }
    }
     
    const array = Array.fromAsync(asyncIterable);
    // [0, 1, 2, 3, 4]

    Simplified Set Manipulation

    Sets get a boost with new methods like union, intersection, and difference, simplifying set manipulation tasks. Check out these examples:

    javascript

    const lts = new Set([18, 20, 22]);
    const nonLts = new Set([17, 19, 21]);
     
    const all = lts.union(nonLts); // all versions [18, 20, 22, 17, 19, 21]
    all.intersection(nonLts); // values in both sets [17, 19, 21]
    all.difference(nonLts); // values not in both sets [18, 20, 22]

    New Iterator Helpers

    Say hello to take, drop, and map - your new best friends for manipulating iterator values. Here's how they roll:

    javascript

    function* fibonacci() {
      let current = 1;
      let next = 1;
      while (true) {
        yield current;
        [current, next] = [next, current + next];
      }
    }
     
    // Print only the first 5 values
    for (const n of fibonacci().take(5)) {
       console.log(n);
    }
     
    // Take the first five elements, then drop the first two
    for (const n of fibonacci().take(5).drop(2)) {
      console.log(n);
    }
     
    // Elevate every number to power of 2
    for (const n of fibonacci().map((x) => x ** 2)) {
      console.log(n);
    }

    Seamlessly Transitioning to ESM Modules

    Are you transitioning from CommonJS to ECMAScript modules? Node.js 22 has your back with the --experimental-require-module flag, enabling synchronous requiring of ESM modules via require().

    Exporting ESM modules and importing in CJS module is a breeze. Check out this example:

    javascript

    // sum.mjs
    export default function sum(a, b) { return a + b }

    And here's how you use it in a CommonJS module:

    javascript

    // index.cjs
    const sum = require('./sum.mjs')
    console.log(sum(1,2)) // it works!

    Simplified WebSocket Client Integration

    In Node.js 22, the WebSocket client is now enabled by default, simplifying development, ensuring compliance with modern web standards and possibly avoiding the need for external libraries.

    javascript

    // Create WebSocket connection
    const socket = new WebSocket("ws://localhost:8080");
     
    // Connection opened
    socket.addEventListener("open", (event) => {
      socket.send("Hello Server!");
    });

    Execute Package.json Scripts with --run Flag

    Executing scripts directly from package.json is now easier than ever with the --run flag, simplifying common tasks and workflows.

    Watch Mode is Now Stable

    Watch Mode has graduated from experimental to stable in Node.js 22, offering automatic restarts for your Node.js process upon file changes.

    If you missed my previous post about watch mode check it here: Streamline your development with Node.js v18's "--watch" and "--watch-path" flags.

    Glob and GlobSync for Efficient Pattern Matching

    Introducing glob and globSync for efficient pattern matching, simplifying file path matching tasks.

    javascript

    import { glob } from 'node:fs';
     
    glob('**/*.js', (err, matches) => {
      if (err) throw err;
      console.log(matches);
    });

    Improved Performance with Maglev Compiler

    The V8 Maglev Compiler enhances performance for short-lived CLI programs, optimizing CPU usage for improved efficiency.

    Stream Default High Water Mark: A Performance Boost

    Increasing the default High Water Mark from 16KiB to 64KiB, enhances performance for applications handling large amounts of data, reflecting advancements in modern hardware capabilities.

    In Conclusion

    Node.js 22 is a significant leap forward, offering a host of new features and enhancements to empower your development process. I hope you're as excited as I am about the possibilities this release brings. Happy coding! 🚀


    Share on