NodeJs is among the dominating development technologies that allow us to create highly appealing web applications. It has given us some of the best giant solutions, like Netflix and Linkdln, which have made things easier. The time-to-time updates and improvement notes garnered its relevance in the development world. All credit goes to their team, who are up with time-to-time changes to make it easy for developers to create high-end applications.
This time, NodeJs has hit up with NodeJs 21 Update on 17th October 2023, packed with exclusive features. This adds stability and improvement to the technology and ease the development process.
The latest Node.js 21 update takes over the position of Node.js 20. Whereas, Node.js 20 is now pushed to the long-term support (LTS). The new upgrade will termed as the ‘Current’ for another six months, approximately till April 2024. There is more to the NodeJs 21 update. Keep reading, as here we will uncover every feature and improvement that comes along with Node.js 21 changes.
About NodeJs
NodeJs is defined as the runtime environment that makes the work easier for a developer to create top of the class server-side and networking apps that go well with any platform. By taking the complete leverage of JavaScript, developers can code Node.js applications compatible with OS X, Windows, and Linux through the Node.js runtime.
On top of providing a broad range of library of JavaScript modules, Node.js gives you the flexibility to streamline web app development.
Exclusive features and improvements in Node.Js 21 Update
As Node.js evolves, it gets more stable, compatible, and usable features and improvements. Now, let’s get into the new features Node.js 21 offers.
Stable Fetch API Status
Node.js introduced the –experimental-fetch flag in v17.5.0 to implement browser-compatible versions of the Fetch API, adding fetch, header, request, and response globals. From version 18.x to version 20.x, there was no need for the flag (but Fetch API was still experimental).
The Fetch API is now stable with Node.js 21. Now that Fetch isn’t experimental anymore, you can use it with confidence:
const res = await fetch(“https://jsonplaceholder.typicode.com/todos/1“);
if (res.ok) { const data = await res.json(); console.log(data); } |
Web Streams API Is Stable
Implementing the Fetch API relies on the AbortController interface (to abort fetch requests) and the Web Streams API, which was added in versions 15.0.0 and 16.5.0, respectively. V15.4.0 AbortController became stable, but Web Streams API is only stable in NodeJs 21.
import { TextDecoderStream } from “node:stream/web”;
async function streamExample() { const response = await fetch(“https://jsonplaceholder.typicode.com/todos/1“); const stream = response.body; const textStream = stream.pipeThrough(new TextDecoderStream()); for await (const chunk of textStream) { console.log(chunk); } } streamExample(); |
There has been no deprecation or removal of the older Node.js streams API. This API works alongside the new API, allowing you to convert Web streams between one another using the .fromWeb() and .toWeb() methods (both new in Node 17 but still in experimental status).
A Built-in WebSocket Client
Adding the –experimental-websocket flag to Node.js continues its commitment to providing standard APIs for web platforms as standardized by WHATWG.
In addition to the new API, existing web platform APIs are available, including the Fetch and Web Stream APIs, an AbortController API, the WHATWG URL parser, and Web Crypto APIs.
// index.js
const socket = new WebSocket(“ws://localhost:8080”); socket.addEventListener(“open”, (event) => { socket.send(“Hello Server!”); }); socket.addEventListener(“message”, (event) => { console.log(“Message from server “, event.data); }); |
While it’s currently not recommended for production use, you can start experimenting with it right away:
node –experimental-websocket index.js |
ES Modules Improvements
With Node.js 21, the experimental-default-type flag lets you modify how input files other than ES modules and CommonJS are processed. This update reverses the previous implicit interpretation of CommonJS input. If you set –experimental-default-type=module, ES modules are supported in the following ways:
Input string provided by –eval or STDIN if –input-type doesn’t specify.
It applies to files ending in .js or without an extension, if there is no package.json in the package or the closest parent field lacks a type value (except if in node_modules).
node –experimental-default-type=module index.js
The improvements pave the way for the eventual support of ES module syntax by default, which requires only minimal changes.
Module Customization Improvements
By removing the confusing globalPreload hook, module customization has been simplified by sending data from application threads into customization hooks and initiating thread-to-thread communication.
llhttp v9.1.2 Strict Mode Enforcement
The Node.js llhttp v9.1.2 update now enforces strict mode by default, allowing it to take advantage of the previously available strict mode features.
There are several noteworthy changes, including a mandatory /r/n presence after headers and chunks and blocking data transmission after a Connection: close header, which increases protocol compliance.
To retain backward compatibility, use the –insecure-http-parser switch to disable these enhancements.
Performance Improvements
With this release, Node.js performance has improved in the following ways:
- To speed up the Streams API, redundant checks were eliminated, bitmaps were utilized, and callbacks were scheduled more efficiently.
- By uncorking responses, chunked responses are avoided by being split into multiple parts, reducing server and client overhead.
V8 Upgraded to v11.8
A JavaScript engine called V8 powers Node.js. V8 compiles and executes JavaScript code and provides various features. Additionally, V8 is used by Chromium, the open-source project that forms the basis of Google Chrome and other browsers.
The Node.js 21 update brings V8 to version 11.8, which is part of Chromium 118. As a result, Node.js will perform better as well as offer new language features, such as:
- Array grouping: It lets you group elements of an array based on a key function or value. In response, it returns an object containing keys that correspond to groups, and values that correspond to arrays of grouped elements.
- ArrayBuffer.prototype.transfer: By using this feature, ArrayBuffer ownership can be transferred to a new buffer of a different size. With a new memory allocation, ArrayBuffer generates a new array containing all the same data as the original array. It is no longer possible to use the original ArrayBuffer once it is detached.
- Error cause: Whenever an Error object is created, you can specify the error’s cause. To add a custom message or the original error to an error object, a cause property is added. Using this method, you can debug and trace errors in complex applications.
Add flush option to writeFile() functions
Node.js now offers a flush option for the fs.writeFile family of functions. A flush option prevents stale data from being encountered during subsequent read operations by forcing data to be flushed after a successful write.
Test Runner Enhancements
With Node.js v21, the native test runner is further improved, building on its stability in v20. With version 21, users can specify multiple glob patterns in the final argument (s).
Here’s an example:
‘node –test */.test.js */.spec.js’. |
The new feature gives end users greater flexibility and control. By allowing users to customize their testing procedures based on the unique needs of their project and structure, it empowers them.
Steps to Upgrade to Node.Js 21 Update
Upgrading to latest version of Node.Js (Nodejs 21 update) brings lots of benefits and you get access to flexibility and enhanced performance. Therefore, it is essential to run through the upgrade for the latest version. Here is the list of basic steps to follow to upgrade to the Node.Js 21 version:
- Install the Node.js 21 installer: At the first step, you are required to navigate to the Node.js official website and download the Node.js 21 installer to begin installation at ease.
- Run the Installer: The next step comes down to running the installer you have installed from the official website. Run the installer and follow the instructions on the screen to install it without any further hassle.
- Re-Check Your Node.js Version: It is great to cross-check for Node.Js version 21 to ensure that you are moving the right path. You need to ensure you have Node.js 21 installed.
By following these easy steps, you can upgrade to the latest version of Node.Js 21 and take complete leverage of latest features and improvements.
Conclusion
NodeJs 21 version updates is sure to surprise you with some best improvements and enhanced performance to take your development to new heights. If you are ready to migrate to Node Js to the latest version, choose a web development company like Hidden Brains and stay ahead with your hands-on improvements and stable updates.