Node.js 15 Released: The Exciting Features You Need to Know

    Tuesday, January 5, 202112 min read4762 views
    Node.js 15 Released: The Exciting Features You Need to Know

    Node.js latest stable version is now available. First introduced in 2009, Node.js has made it to the latest version, version 15. The release of the JavaScript runtime Node.js 15 will replace Node.js 14 on the team’s current release line where Node.js 14 has been moved to long-term support.  node Node.js is an open-source, back-end, and cross-stage JavaScript runtime environment utilized by countless organizations. 

    Node 15 has an offbeat IO and an event-driven design, that makes ongoing web application improvement simpler than at any other time. Node.js is favoured by the widely acclaimed brands, Fortune 500 organizations, new companies, and medium-sized associations. It represents the 'JavaScript Everywhere' worldview for complete web advancement instead of utilizing various dialects for the frontend and backend.

    Node Version 15 features several improvements along with some new JavaScript language features, and even some breaking changes. The support for npm 7 with long-awaited features is one of the important features of Node 15. It helps to substantially and dramatically improve the developer experience. The experimental support for the QUIC protocol and the new version of the N-API are some of the breaking changes that may not appeal to the masses but are equally important as the other features to ensure that Node.js continues to be extensible and prepared for the future of the web. In this blog, we look into the above features of Node 15 and some of the breaking changes that have captivated the market.

    The Exciting Features of Node. js 15

    NPM 7

    The introduction of the NPM is one of the biggest headliners of the current node version. NPM is the package manager of the javascript programme language which makes it one of the largest software registries. Npm 7 has many long-awaited features. Among the bevy of new features, workspace is the biggest of all which supports the NPM packages creation and management in a single file system. Every Node.js development company is actively looking for similarities with NPM’s workspace implementation and the Yarn package manager. There have been significant internal changes in NPM 7 that ensure codebase reliability and maintainability. Some of the notable features of NPM 7 are:

    Workplaces-: Manage different bundles from inside a  singular top-level, root bundle. This is one of the most awaited components in the network. It is a new package-lock.json format, that supports yarn.lock file, and automatic installation of peer dependencies.

    Default Peer dependencies -: previously NPM used to manually install a peer dependency to resolve the issue missing peer dependencies. The current version of NPM is more intelligent about this and naturally introduces peer conditions for you. 

    Package-lock.json v2 and yarn.lock support- The new package-lock format promises to deliver deterministically reproducible builds. NPM will currently utilize the yarn.lock file if present to help in building the dependency tree.

    It is relatively easy to get started with NPM workspaces. First, arrange all your NPM package folders on the file system, create a top-level package.json that refers to each of these folders, and start running commands across all NPM packages.

    Abort Controller

    The current node version introduces an experimental implementation of AbortController. It is used for cancelling specific promise-based APIs. It is a worldwide utility class dependent on the web API. The AbortController permits developers to prematurely end at least one Web request as and when required. let's comprehend through the beneath model.

    AbortController


    The cancellation feature that has been discussed for a long time is finally implemented by the AbortController.  The list of promising APIs that support the abort feature, is sure to expand in the future, as the feature matures into stability.  Since the feature is experimental, the final API can appear different. It is advisable to not use it in production until the feature has been stabilised.

    The recommended way to timeout a request while using node-fetch  is as follows:

    const fetch = require('node-fetch');
    const controller = new AbortController();

    // Abort after 5 secondssetTimeout(() =>
    controller.abort(), 5000);
    try { // Pass the signal to fetch so it can listen to the abort event
    const response = await fetch('https://example.com', {
    signal: controller.signal });

    // Do something with the response..}
    catch (error) {
    if (error.name === 'AbortError') {
    console.log('Request was aborted'); }
    }

    Experimental Support for QUIC Protocol (HTTP/3)

    Node.js 15 features the support for QUICprotocol. QUIC is a UDP-based organization transport convention for HTTP/3 that provides built-in security with TLS 1.3, multiplexing, stream control, error adjustment, connection relocation, etc. Node.js 15 accompanies experimental support for this through the QUIC configuration flag.

    QUIC is an exploratory, broadly useful, transport layer network protocol planned by Google. It is quicker, proficient, and like the TCP+TLS+HTTP/2 protocol actualized on UDP. It intends to reduce latency contrasted with TCP.

    Node.js community is one of the strong communities with a steady chain of enhancements and improvements, bug fixes, and plans to update Node.js.

    The Node.js QUIC implementation is uncovered by the center net module:

    const { createQuicSocket } = require(‘net’);

    It is advisable to use the net module for creating sockets in your application. The new set of experimental functions and objects are advantageous to establish connections using the QUIC protocol. 

    hire node developers


    Additional QUIC advantages::

    • Flow Control
    • Error correction
    • Connection Migration
    • TLS 1.3
    • Multiplexing

    Read More: The Exciting Features of Node. js 14

    New Language Features with v8.6

    Node's latest version, Node.js 15 has now V8 JavaScript runtime support. It has been refreshed to 8.6 from 8.4 with numerous performance upgrades and highlights. Node.js 15 bumps the version V8 engine it utilizes from 8.4 to 8.6. V8, that is the basic JavaScript engine that Node.js runs on. This is because V8 characterizes the JavaScript language features that are available to developers. While this version bump is little, there are a couple of new dialects includes that will diminish the measure of code you need to compose and conceivably make your code more intelligible.

    Here are  some new logical assignment operators that let you assign a value to a variable conditionally:

    // new logical AND operator 
    let a = 1;
    let b = 0;
    a &&= 2;
    b &&= 2;
    console.log(a);// prints 2
    console.log(b); // prints 0
    // new logical OR operator
    a = 1;
    b = null;
    a ||= 3;
    b ||= 3;
    console.log(a); // prints 1
    console.log(b); // prints 3
    // new logical nullish operator
    a = 1;
    b = null;
    a ??= 4;
    b ??= 4;console.log(a); // prints 1
    console.log(b); // prints 4

    The Promise object has another any() work that acknowledges at least one promise and returns the promise that settles first. It ignores the promises that are rejected. If all promises are dismissed, another AggregateError is returned containing the mistakes from all the rejected promises

    There are numerous developers that don't have ordinary articulation sentence structure focused on their minds. Fortunately, the String object presently has another replaceAll() work, which implies there is one less normal articulation that you need to look up to replace all occurrences of a string.

    It's Run as: myString.replaceAll(``'``regex``'``, '``function``'``).

    Unhandled Rejections are Thrown

    One of the biggest breaking changes in the latest version of Node.js is how unhandled rejected promises are managed. In the previous version, you will get to see a warning if you did not explicitly handle a rejected promise. 

    The default mode for unhandledRejection is changed to raise an uncaught exception and terminate the application. in Node.js 15. This choice depends on the consequences of the Node.js User Insights: Unhandled Promise Rejections study and a Node.js Technical Steering Committee vote. Node.js now is changed to throw a warning which can be a nasty surprise in production if Node.js is updated  without being aware of this change. 

    By adding a global handler of the unhandledRejection event, you can get unhandled rejections and choose how you need to continue. The accompanying code will basically log the occasion and keep the application running, like the conduct of prior Node.js variants:

    // Global handler for unhandled promise rejections 
    process.on('unhandledRejection', (reason, promise) => {
    console.log('Unhandled Rejection at:', promise, 'reason:', reason);// Decide whether to:
    // 1. Do nothing and keep the application running or
    // 2. Exit with `process.exit(1)` and let a process manager automatically restart the application});

    The recommended methodology is to allow the application to crash since it might be in a faulty state that may prompt more errors and weird bugs. If you allow the application to crash, ensure you're utilizing a process manager that will naturally restart your application. 

    It's ideal to deal with rejection as close as conceivable to the spot it was thrown. You can set up alarms in production and track down unhandled rejections that you neglected to get in your code.

    Experimental Diagnostics Channel Module

    Another feature of Node.js 15 is that it presents another trial module named diagnostics_channel. This module basically empowers a publish-subscribe pattern that engineers can use to distribute arbitrary information to a channel that can be devoured by different modules or applications. The module is purposefully nonexclusive and could be utilized in an assortment of ways.

    Users can import and begin utilizing the module immediately:

    const diagnostics_channel = require('diagnostics_channel');

    Making a channel and distributing a message to it is in reality very simple. This model exhibits making a channel and distributing a message to it:

    const getData = filter => {
    const alertChannel = diagnostics_channel.channel('my-module.alert');
    return new Promise((resolve, reject) => {
    const data = doSomething(filter);
    if (data) {
    resolve(data);
    } else {
    const errorMessage = "data could not be retrieved";
    alertChannel.publish(errorMessage);
    reject(errorMessage);
    }
    });
    }

    Consuming messages from the channel is pretty simple. Here's an illustration of how you can buy into a channel from another module or application and utilize the information received from the channel:

     const alertChannel = diagnostics_channel.channel('my-module.alert');
    alertChannel.subscribe(message => {
    console.log(`Alert received on my-module.alert channel: ${message}`);
    });

    N-API Version 7

    Node.js 15 changes make it simpler to make, assemble, and uphold local modules (otherwise called add-ons). IBM and Red Hat are continuous supporters of N-API, and Node latest version  accompanies N-API version 7, which carries extra techniques for working with array buffers:

    napi_status napi_detach_arraybuffer(napi_env env,
    napi_value arraybuffer)
    napi_status napi_is_detached_arraybuffer(napi_env env,
    napi_value arraybuffer,
    bool* result)

    Of note,  node-addon-api, is one of the approaches to burn-through N-API, has seemed to surpass 2 million downloads recently,  every week! For more data about N-API, look at the API docs and node-addon-api.

    Native promise API for setTimeout

    If you have completely embraced promises and async/await in your codebase, setTimeout is one of the last places where you actually need to utilize the callback design:

    console.log('Starting async operation..');
    setTimeout(() => {
    console.log('Async done!');
    }, 1000);

    Node 15  features a promisified setTimeout that comes with a util module, using a 3rd party library as an alternative. With Node.js 15 and up, you can supplant these workarounds with a native arrangement.

    Node latest stable version ships with the Timers Promises API that has a promisified variant of setTimeout:

    const { setTimeout } = require('timers/promises');
    console.log('Starting async operation..');
    await setTimeout(1000);
    console.log('Async done!');

    However, we need to keep in mind that this Node 15 feature is in the experimental stage.

    Refinement of the Async Local Storage APIs

    The addition of the Async Local Storage API is one of the most important features of Node 15  for enterprise customers that need cross-process transaction following and more profound bits of knowledge in their enormous applications.

    This is an important feature for enterprise customers that need cross-process transaction tracing and deeper insights into their large applications. It will guarantee Node.js gives supported APIs and a top-notch insight for organizations utilizing open-source arrangements like OpenTelemetry, just as other application performance management solutions (APMs).

    What’s Next?

    The Node latest stable version, Node 15 is focused more on improving the contribution process. To decide the next area of improvement, the Node.js community has led one study to assemble criticism on the contribution process. There have been a few upgrades for computerization and tooling, bringing about simple coordinated effort and management.  As Node.js marks 11 years of its existence, it is intriguing to perceive how the Node.js community sets the direction of success in the impending years.


    Read More: Why To Choose Node.js For Server Side Programming

    Related articles