The Node.js 23 version brings numerous new features and improvements to developers. Let's take an in-depth look at these changes and showcase how to use these new features through practical code examples.
Built-in WebSocket Client API
Node.js 23 now has a built-in WebSocket client API, eliminating the need to use third-party libraries. This significantly simplifies the use of WebSocket.
Example code:
// Code interpretationconst WebSocket = require("node:ws");const ws = new WebSocket("ws://example.com:8080");ws.on("open", function open() { console.log("Connection established"); ws.send("Hello, server!");});ws.on("message", function incoming(data) { console.log("Received message:", data.toString());});ws.on("close", function close() { console.log("Connection closed");});
Web Streams API
Node.js 23 introduces the Web Streams API, making it more convenient to handle stream data.
Example code:
// Code interpretationconst { ReadableStream, WritableStream, TransformStream } = require("node:stream/web");const readableStream = new ReadableStream({ start(controller) { controller.enqueue("Hello"); controller.enqueue("World"); controller.close(); },});const transformStream = new TransformStream({ transform(chunk, controller) { controller.enqueue(chunk.toUpperCase()); },});const writableStream = new WritableStream({ write(chunk) { console.log(chunk); },});readableStream.pipeThrough(transformStream).pipeTo(writableStream);
Global Blob and BroadcastChannel API
The Blob and BroadcastChannel APIs can now be used globally.
Blob example:
// Code interpretationconst blob = new Blob(["Hello, World!"], { type: "text/plain" });const text = await blob.text();console.log(text); // Output: Hello, World!
BroadcastChannel example:
// Code interpretationconst channel = new BroadcastChannel("test_channel");channel.postMessage("Hello, channel!");channel.onmessage = (event) => { console.log("Received message:", event.data);};
Native ESM Support
Node.js 23 further enhances support for ECMAScript modules (ESM).
Example code (math.mjs):
// Code interpretationexport function add(a, b) { return a + b;}export function multiply(a, b) { return a * b;}
Using the module (main.mjs):
// Code interpretationimport { add, multiply } from "./math.mjs";console.log(add(5, 3)); // Output: 8console.log(multiply(4, 2)); // Output: 8
Experimental TypeScript Stripping
Node.js 23 introduces the experimental TypeScript stripping feature, allowing you to run TypeScript files directly.
Example code (hello.ts):
// Code interpretationfunction greet(name: string): string { return `Hello, ${name}!`;}console.log(greet("Zhang San"));
Running command:
# Code interpretationnode --experimental-strip-types hello.ts
Built-in File Watching
Node.js 23 has a built-in file-watching feature, eliminating the need to use third-party tools like nodemon.
Example code (app.js):
// Code interpretationconsole.log("Server is running...");// Simulate server logicsetInterval(() => { console.log("Processing requests...");}, 2000);
Running command:
# Code interpretationnode --watch app.js
Now, whenever you modify the app.js file, Node.js will automatically restart the application.
Native Environment Variable Support
Node.js 23 supports directly loading.env files without the need for libraries like dotenv.
Example.env file:
# Code interpretationDB_HOST=localhostDB_USER=rootDB_PASS=password123
Example code (config.js):
// Code interpretationconsole.log(process.env.DB_HOST);console.log(process.env.DB_USER);console.log(process.env.DB_PASS);
Running command:
# Code interpretationnode --env-file=.env config.js
Test Runner Module
Node.js 23 introduces the experimental node:test module, facilitating the creation and running of JavaScript tests.
Example code (test.js):
// Code interpretationconst test = require("node:test");const assert = require("node:assert");test("Simple addition test", (t) => { assert.strictEqual(1 + 2, 3);});test("Asynchronous test", async (t) => { const result = await Promise.resolve(42); assert.strictEqual(result, 42);});
Running tests:
# Code interpretationnode --test test.js
These new features and improvements make Node.js 23 a more powerful and user-friendly JavaScript runtime environment. Through these practical code examples, developers can better understand and utilize these new functions, improving development efficiency and code quality.