Our Global Presence
Canada
57 Sherway St,
Stoney Creek, ON
L8J 0J3
India
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
USA
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
Node.js 21 was released on October 17, 2023 and came with a number of new features and improvements. This includes experimental support for the WebSocket API, a new –experimental-default-type flag, and a number of updates to the test runner and llhttp parser.
Node.js 21 introduces experimental support for the WebSocket API, which allows you to connect to a WebSocket server from a Node.js application without resorting to third-party packages. This is an important innovation, as it allows real-time, two-way interactive communication between the client and server.
const WebSocket = require('ws'); const ws = new WebSocket('ws://localhost:8080'); ws.on('open', () => { console.log('WebSocket connection open'); }); ws.on('message', (message) => { console.log('Received message:', message); }); ws.on('close', () => { console.log('WebSocket connection closed'); });
By default, Node.js will interpret any code you enter or send it as an ES module if you do not specify otherwise, and if the package.json file is not present. The new –experimental-default-type flag allows you to override this behavior and specify that code should be interpreted as CommonJS instead.
To use the –experimental-default-type flag, you can use the following command:
node --experimental-default-type=commonjs my-script.js
This will cause the my-script.js file to be interpreted as CommonJS, even if it does not have an .extensions file extension.
Node.js 21 introduces a new –test-concurrency flag that allows you to specify the number of parallel processes that the test runner should use. This can be useful for improving performance on machines with multiple cores.
To use the –test-concurrency flag, you can use the following command:
node --test-concurrency=4 test
This will cause the test runner to execute tests in parallel using four processes.
Node.js 21 now supports passing globs as arguments to the test runner. This allows you to specify which test files to run based on patterns, rather than having to specify each file individually.
To run all test files that match the *.test.js pattern, you can use the following command:
node test *.test.js
Node.js 21 uses llhttp version 9.1.2, which introduces a number of new features and bug fixes. One of the most important changes is that llhttp 9.1.2 now has a strict mode that is enabled by default. This means that llhttp will now reject requests that are not formatted correctly.
If you are using a third-party library that sends malformed requests, you may need to disable strict mode in order to use it. To do this, you can use the following command:
node --insecure-http-parser my-script.js
Node.js 21 is a significant release that includes a number of new features and improvements. The experimental support for the WebSocket API is particularly exciting, as it opens up new possibilities for real-time applications.
For more information, please head over to our Hire Node Developer page and to develop a web application using Node JS, Hire Node Developer at HK Infosoft – we are destined to provide you with an innovative solution using the latest technology stacks. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop Android Mobile Apps, please visit our technology page.
Content Source:
In the rapidly evolving world of web development, developers are constantly on the lookout for frameworks that can provide both speed and efficiency. Enter Fastify, a lightweight and lightning-fast web framework for Node.js that has taken the development community by storm. If you’re a developer looking to create high-performance, scalable, and secure web applications, Fastify may be the game-changer you’ve been waiting for.
Fastify, developed by Matteo Collina and Tomas Della Vedova, is an open-source web framework for Node.js designed with a primary focus on speed and low overhead. Launched in 2016, Fastify has quickly gained popularity in the Node.js ecosystem due to its impressive performance, simplicity, and extensibility. It is built on top of Node.js’s HTTP module and takes full advantage of the latest JavaScript features to maximize its speed and efficiency.
// Require the framework and instantiate it const fastify = require("fastify")({ logger: true }); // Declare a rout fastify.get("/", async (request, reply) => { return { hello: "world" }; }); // Start the server fastify.listen(3000);
One of the primary reasons developers are flocking to Fastify is its exceptional performance. Thanks to its powerful and highly optimized core, Fastify boasts some of the fastest request/response times among Node.js frameworks. It leverages features like request validation, which is automatically generated from JSON schemas, to ensure that data is processed swiftly and accurately. Additionally, Fastify supports asynchronous programming and handles requests concurrently, making it ideal for handling heavy workloads and high traffic.
Fastify follows a minimalist approach, focusing on providing only the essential components needed to build web applications efficiently. Developers can opt-in to use various plugins to extend Fastify’s functionality as per their requirements. This approach not only keeps the core lightweight but also gives developers the flexibility to customize their stack with the specific tools they need. Furthermore, the ecosystem around Fastify is growing rapidly, with a wide array of plugins and middleware available, making it easy to integrate third-party tools seamlessly.
Fastify’s API is designed to be intuitive and easy to use, reducing the learning curve for developers. Its well-documented and expressive API allows developers to write clean, maintainable, and organized code. The framework’s emphasis on proper error handling and logging also contributes to its ease of use, helping developers quickly identify and rectify issues during development and production.
Data validation is a crucial aspect of web application development to ensure data integrity and security. Fastify utilizes JSON Schema for data validation, enabling developers to define the expected shape of incoming requests and responses. This not only simplifies the validation process but also automatically generates detailed and helpful error messages, making debugging a breeze.
Fastify is designed with security in mind. It encourages best practices such as using the latest cryptographic libraries and secure authentication mechanisms. Additionally, Fastify has a built-in protection mechanism against common web application attacks like Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF). With Fastify, developers can rest assured that their applications are less prone to security vulnerabilities.
Fastify’s emergence as a top-tier web framework for Node.js is no coincidence. Its commitment to speed, minimalism, and extensibility sets it apart from the competition. Whether you’re building a small-scale API or a large-scale application, Fastify’s performance, easy-to-use API, and emphasis on security make it an excellent choice.
In the fast-paced world of web development, having a framework that can boost productivity and deliver top-notch performance is essential. Fastify has proven itself as a reliable and efficient framework, providing developers with the tools they need to create high-performance applications without compromising on code quality and security.
So, if you’re ready to take your Node.js projects to the next level, give Fastify a try, and experience the speed and power it brings to your development workflow.
For more information and to develop web applications using Node.js, Hire Node.js Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop custom web apps using Node.js, please visit our technology page.
Content Source:
In the realm of server-side JavaScript, Node.js has become a dominant force, revolutionizing the way we build web applications. With each new version, Node.js brings forth exciting enhancements, improved performance, and expanded capabilities. In this blog, we’ll embark on a journey through the evolution of Node.js, exploring the advancements that have led to the highly anticipated Node 20. We’ll delve into the key features of Node 20 and showcase an example that demonstrates its potential.
Since its initial release in 2009, Node.js has evolved significantly, shaping the landscape of JavaScript development. The first versions of Node.js introduced a non-blocking, event-driven architecture, enabling developers to build highly scalable and efficient applications. With its growing popularity, Node.js gained a vibrant ecosystem of modules and libraries, making it a versatile platform for both back-end and full-stack development.
As Node.js progressed, new features were introduced to enhance performance, security, and developer productivity. For instance, Node.js 8 introduced the Long-Term Support (LTS) release, which provided stability and backward compatibility. Node.js 10 brought improvements in error handling and diagnostic reports, making it easier to identify and resolve issues. Node.js 12 introduced enhanced default heap limits and improved performance metrics.
Now, let’s turn our attention to Node 20, the latest iteration of Node.js, and explore its groundbreaking features that are set to shape the future of JavaScript development.
– Improved Performance and Speed:
– Enhanced Security:
– Improved Debugging Capabilities:
– ECMAScript Modules (ESM) Support:
– Enhanced Worker Threads:
– Stable Test Runner
– url.parse() Warns URLs With Ports That Are Not Numbers
Let’s explore what they are and how to use them.
– Node.js 20 incorporates the latest advancements in the V8 JavaScript engine, resulting in significant performance improvements. Let’s take a look at an example:
// File: server.js const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello, world!'); }); server.listen(3000, () => { console.log('Server running on port 3000'); });
By leveraging the performance optimizations in Node.js 20, applications like the one above experience reduced response times and enhanced scalability, resulting in an improved user experience.
Security is a top priority for any application, and Node.js 20 introduces several features to bolster its security. One noteworthy enhancement is the upgraded TLS implementation, ensuring secure communication between servers and clients. Here’s an example of using TLS in Node.js 20:
// File: server.js const https = require('https'); const fs = require('fs'); const options = { key: fs.readFileSync('private.key'), cert: fs.readFileSync('certificate.crt') }; const server = https.createServer(options, (req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Secure Hello, world!'); }); server.listen(3000, () => { console.log('Server running on port 3000'); });
With the upgraded TLS implementation, Node.js 20 ensures secure data transmission, safeguarding sensitive information.
Node.js 20 introduces enhanced diagnostic and debugging capabilities, empowering developers to pinpoint and resolve issues more effectively. Consider the following example:
// File: server.js const { performance, PerformanceObserver } = require('perf_hooks'); const obs = new PerformanceObserver((items) => { console.log(items.getEntries()[0].duration); performance.clearMarks(); }); obs.observe({ entryTypes: ['measure'] }); performance.mark('start'); // ... Code to be measured ... performance.mark('end'); performance.measure('Duration', 'start', 'end');
In this example, the Performance API allows developers to measure the execution time of specific code sections, enabling efficient optimization and debugging.
Node.js 20 embraces ECMAScript Modules (ESM), providing a standardized approach to organize and reuse JavaScript code. Let’s take a look at an example:
// File: module.js export function greet(name) { return `Hello, ${name}!`; } // File: app.js import { greet } from './module.js'; console.log(greet('John'));
With ESM support, developers can now leverage the benefits of code encapsulation and organization in Node.js, facilitating better code reuse and maintenance.
Node.js 20 introduces improved worker threads, enabling true multi-threading capabilities within a Node.js application. Consider the following example:
// File: worker.js const { Worker, isMainThread, parentPort, workerData } = require('worker_threads'); if (isMainThread) { const worker = new Worker(__filename, { workerData: 'Hello, worker!' }); worker.on('message', message => console.log(message)); } else { parentPort.postMessage(workerData); }
In this example, the main thread creates a worker thread that receives data and sends a message back. With enhanced worker threads, Node.js 20 empowers developers to harness the full potential of multi-core processors, improving application performance.
Node.js 20 includes an important change to the test_runner module. The module has been marked as stable after a recent update. Previously, the test_runner module was experimental, but this change marks it as a stable module ready for production use.
url.parse() accepts URLs with ports that are not numbers. This behavior might result in hostname spoofing with unexpected input. These URLs will throw an error in future versions of Node.js, as the WHATWG URL API already does. Starting with Node.js 20, these URLS cause url.parse() to emit a warning.
Here is urlParse.js:
const url = require('node:url'); url.parse('https://example.com:80/some/path?pageNumber=5'); // no warning url.parse('https://example.com:abc/some/path?pageNumber=5'); // show warning
Execute node urlParse.js . https://example.com:80/some/path?pageNumber=5 with a numerical port does not show a warning, but https://example.com:abc/some/path?pageNumber=5 with a string port shows a warning.
% node urlParse.js (node:21534) [DEP0170] DeprecationWarning: The URL https://example.com:abc/some/path?pageNumber=5 is invalid. Future versions of Node.js will throw an error. (Use `node --trace-deprecation ...` to show where the warning was created)
Conclusion
Node.js 20 brings a plethora of innovative features and enhancements that revolutionize the way developers build applications. Improved performance, enhanced security, advanced debugging capabilities, ECMAScript Modules support, and enhanced worker threads open up new possibilities for creating scalable, secure, and high-performing applications. By leveraging these cutting-edge features, developers can stay at the forefront of modern web development and deliver exceptional user experiences. Upgrade to Node.js 20 today and unlock a new era of JavaScript development!
For more information and to develop web applications using Node JS, Hire Node Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop your custom web app using Node JS, please visit our technology page.
Content Source:
Node.js major release is rolled out every six months. The new release becomes the Current release for six months, which gives library authors time to add support for them.
After six months, odd-numbered releases, such as 19, become unsupported, and even-numbered releases, such as 18, move to the Active LTS (long-term support) status and are ready for general use.
LTS release typically guarantees that critical bugs will be fixed for a total of 30 months. Production applications should only use Active LTS or Maintenance LTS releases.
Node.js 19 was released recently which comes with 6 major features:
Let’s explore what they are and how to use them.
Run the command to install node 19.0.0:
% nvm install 19.0.0 Downloading and installing node v19.0.0... Downloading https: //nodejs.org/dist/v19.0.0/node-v19.0.0-darwin-x64.tar.xz... Computing checksum with sha256sum Checksums matched! Now using node v19.0.0 (npm v8.19.2) |
On any window, run the command to use node 19:
% nvm use 19 Now using node v19.0.0 (npm v8.19.2) |
Now you’re ready to explore:
% node --version v19.0.0 |
In A Hands-on Guide for a Server-Side Rendering React 18 App, you have to build a production Create React App by executing npm run build.
You can created server/index.js:
const express = require ( "express" ); const path = require ( "path" ); const app = express(); app. use (express. static (path.join(__dirname, "../build" ))); app.listen(8080, () => console.log( "Express server is running on localhost:8080" ) ); |
The server was running with nodemon, a tool that helps to develop Node.js applications by automatically restarting the application when file changes are detected. The command is nodemon server.
With node.js 19, you no longer need to install the additional tool. Instead, you can execute node –watch to automatically restart the application when file changes are detected.
% node --watch server (node:67643) ExperimentalWarning: Watch mode is an experimental feature. This feature could change at any time (Use `node --trace-warnings ...` to show where the warning was created) Express server is running on localhost:8080 |
Node.js 19 sets keepAlive to true by default. This means that any outgoing HTTP(s) connection will automatically use HTTP 1.1 keepAlive. The default keepAlive duration is 5 seconds.
Change the above server/index.js to:
const http = require ( 'node:http' ); console.log(http.globalAgent); const https = require ( 'node:https' ); console.log(https.globalAgent); |
Execute the server code using node.js 16:
% nvm use 16 Now using node v16.0.0 (npm v7.10.0) % node server Agent { _events: [Object: null prototype] { free: [Function (anonymous)], newListener: [Function: maybeEnableKeylog] }, _eventsCount: 2, _maxListeners: undefined, defaultPort: 80, protocol: 'http:' , options: [Object: null prototype] { path: null }, requests: [Object: null prototype] {}, sockets: [Object: null prototype] {}, freeSockets: [Object: null prototype] {}, keepAliveMsecs: 1000, keepAlive: false, maxSockets: Infinity, maxFreeSockets: 256, scheduling: 'lifo' , maxTotalSockets: Infinity, totalSocketCount: 0, [Symbol(kCapture)]: false } Agent { _events: [Object: null prototype] { free: [Function (anonymous)], newListener: [Function: maybeEnableKeylog] }, _eventsCount: 2, _maxListeners: undefined, defaultPort: 443, protocol: 'https:' , options: [Object: null prototype] { path: null }, requests: [Object: null prototype] {}, sockets: [Object: null prototype] {}, freeSockets: [Object: null prototype] {}, keepAliveMsecs: 1000, keepAlive: false, maxSockets: Infinity, maxFreeSockets: 256, scheduling: 'lifo' , maxTotalSockets: Infinity, totalSocketCount: 0, maxCachedSessions: 100, _sessionCache: { map: {}, list: [] }, [Symbol(kCapture)]: false } |
Execute the server code using node.js 19:
% nvm use 19 Now using node v19.0.0 (npm v8.19.2) % node server Agent { _events: [Object: null prototype] { free: [Function (anonymous)], newListener: [Function: maybeEnableKeylog] }, _eventsCount: 2, _maxListeners: undefined, defaultPort: 80, protocol: 'http:' , options: [Object: null prototype] { keepAlive: true, scheduling: 'lifo' , timeout: 5000, noDelay: true, path: null }, requests: [Object: null prototype] {}, sockets: [Object: null prototype] {}, freeSockets: [Object: null prototype] {}, keepAliveMsecs: 1000, keepAlive: true, maxSockets: Infinity, maxFreeSockets: 256, scheduling: 'lifo' , maxTotalSockets: Infinity, totalSocketCount: 0, [Symbol(kCapture)]: false } Agent { _events: [Object: null prototype] { free: [Function (anonymous)], newListener: [Function: maybeEnableKeylog] }, _eventsCount: 2, _maxListeners: undefined, defaultPort: 443, protocol: 'https:' , options: [Object: null prototype] { keepAlive: true, scheduling: 'lifo' , timeout: 5000, noDelay: true, path: null }, requests: [Object: null prototype] {}, sockets: [Object: null prototype] {}, freeSockets: [Object: null prototype] {}, keepAliveMsecs: 1000, keepAlive: true, maxSockets: Infinity, maxFreeSockets: 256, scheduling: 'lifo' , maxTotalSockets: Infinity, totalSocketCount: 0, maxCachedSessions: 100, _sessionCache: { map: {}, list: [] }, [Symbol(kCapture)]: false } |
Enable keepAlive will deliver better throughput as connections are reused by default.
Additionally, the agent is able to parse the response keepAlive that the servers might send. This header instructs the client on how much longer to stay connected.
On the other side, the HTTP server will automatically disconnect idle clients when close() is invoked. It is accomplished by http(s).Server.close calling closeIdleConnections internally.
With these changes, HTTP(S)/1.1 requests may experience a better throughput/performance by default.
The WebCrypto API is an interface to build systems using cryptography. With node.js 19, the WebCrypto API is stable (with the exception of these algorithms: Ed25519, Ed448, X25519, and X448).
You can use globalThis.crypto or require(‘node:crypto’).webcrypto to access this module. The following server/index.js use subtle as an example, where the SubtleCrypto interface provides a number of low-level cryptographic functions:
const { subtle } = globalThis.crypto; (async function () { const key = await subtle.generateKey({ name: 'HMAC' , hash: 'SHA-256' , length: 256 }, true, [ 'sign' , 'verify' ]); console.log( 'key =' , key); const enc = new TextEncoder(); const message = enc.encode( 'I love cupcakes' ); console.log( 'message =' , message); const digest = await subtle.sign({ name: 'HMAC' }, key, message); console.log( 'digest =' , digest); })(); |
The following console information shows the values of key, message, and digest:
% node server key = CryptoKey { type: 'secret' , extractable: true, algorithm: { name: 'HMAC' , length: 256, hash: [Object] }, usages: [ 'sign' , 'verify' ] } message = Uint8Array(15) [ 73, 32, 108, 111, 118, 101, 32, 99, 117, 112, 99, 97, 107, 101, 115 ] digest = ArrayBuffer { [Uint8Contents]: <30 01 7a 5c d9 e2 82 55 6b 55 90 4f 1d de 36 d7 89 dd fb fb 1a 9e a0 cc 5d d8 49 13 38 2f d1 bc>, byteLength: 32 } |
Node.js has removed the –experimental-specifier-resolution flag, because its functionality can be achieved via custom loaders.
Clone the example repository:
git clone https://github.com/nodejs/loaders-test.git
Go to the example directory:
% cd loaders-test/commonjs-extension-resolution-loader
Install the packages:
% yarn install
Here is loaders-test/commonjs-extension-resolution-loader/test/basic-fixtures/index.js:
import { version } from 'process' ; import { valueInFile } from './file' ; import { valueInFolderIndex } from './folder' ; console.log(valueInFile); console.log(valueInFolderIndex); |
Here is loaders-test/commonjs-extension-resolution-loader/test/basic-fixtures/file.js:
export const valueInFile = ‘hello from file.js’;
Here is loaders-test/commonjs-extension-resolution-loader/test/basic-fixtures/folder/index.js:
export const valueInFolderIndex = ‘hello from folder/index.js’;
We have mentioned in another article that there are two ways to execute ESM code:
Regardless, the following two commands will fail.
% node test/basic-fixtures/index % node test/basic-fixtures/index.js
However, all these issues can be resolved by the custom loader, loaders-test/commonjs-extension-resolution-loader/loader.js:
import { isBuiltin } from 'node:module' ; import { dirname } from 'node:path' ; import { cwd } from 'node:process' ; import { fileURLToPath, pathToFileURL } from 'node:url' ; import { promisify } from 'node:util' ; import resolveCallback from 'resolve/async.js' ; const resolveAsync = promisify(resolveCallback); const baseURL = pathToFileURL(cwd() + '/' ).href; export async function resolve(specifier, context, next) { const { parentURL = baseURL } = context; if (isBuiltin(specifier)) { return next(specifier, context); } // `resolveAsync` works with paths, not URLs if (specifier.startsWith( 'file://' )) { specifier = fileURLToPath(specifier); } const parentPath = fileURLToPath(parentURL); let url; try { const resolution = await resolveAsync(specifier, { basedir: dirname(parentPath), // For whatever reason, --experimental-specifier-resolution=node doesn't search for .mjs extensions // but it does search for index.mjs files within directories extensions: [ '.js' , '.json' , '.node' , '.mjs' ], }); url = pathToFileURL(resolution).href; } catch (error) { if (error.code === 'MODULE_NOT_FOUND' ) { // Match Node's error code error.code = 'ERR_MODULE_NOT_FOUND' ; } throw error; } return next(url, context); } |
With the loader, the above failed commands work well:
% node --loader=./loader.js test/basic-fixtures/index (node:56149) ExperimentalWarning: Custom ESM Loaders is an experimental feature. This feature could change at any time (Use `node --trace-warnings ...` to show where the warning was created) hello from file.js hello from folder/index.js % node --loader=./loader.js test/basic-fixtures/index.js (node:56160) ExperimentalWarning: Custom ESM Loaders is an experimental feature. This feature could change at any time (Use `node --trace-warnings ...` to show where the warning was created) hello from file.js hello from folder/index.js |
With custom loaders, there is no need for the –experimental-specifier-resolution flag.
For the following two reasons, Node.js has dropped the support for DTrace/SystemTap/ETW:
Node.js 19 has updated V8 JavaScript engine to V8 10.7, which includes a new function, Intl.NumberFormat, for language-sensitive number formatting.
Intl.NumberFormat(locales, options)
locales is an optional parameter, which is a BCP 47 language tag, or an array of such strings. Here is the BCP 47 language tag list:
options is also an optional parameter, which is an object with some or all of these properties: compactDisplay, currency, currencyDisplay, currencySign, localeMatcher, notation, numberingSystem, signDisplay, style, unit, unitDisplay, useGrouping, roundingMode, roundingPriority, roundingIncrement, trailingZeroDisplay, minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, minimumSignificantDigits, and maximumSignificantDigits.
Among them, style chooses the formatting style, with the following supported values:
If style is set to ‘currency’, the currency property is required. currency takes ISO 4217 currency code that is listed in this table. By default, minimumFractionDigits and maximumFractionDigits are both set to 2.
Let’s take a look at this example:
const number = 123456.789; console.log( new Intl.NumberFormat( 'de-DE' , { style: 'currency' , currency: 'EUR' }).format(number)); console.log( new Intl.NumberFormat( 'ja-JP' , { style: 'currency' , currency: 'JPY' }).format(number)); console.log( new Intl.NumberFormat( 'ar-SA' , { style: 'currency' , currency: 'EGP' }).format(number)); console.log( new Intl.NumberFormat( 'zh-CN' , { style: 'currency' , currency: 'CNY' }).format(number)); |
For more information and to develop web applications using Node JS, Hire Node Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop your custom web app using Node JS, please visit our technology page.
Content Source:
Cron Jobs in node.js is used for scheduling scripts to run, They’re most commonly used for automating doing a task like scraping data from another website, deleting some data from the database, etc. However, there are many situations when a web application may need specific tasks to run periodically.
In this article, the points to cover are:
There are three popular modules that are sorted based on GitHub starts
But the number of downloads cron is more than other modules currently.
All three modules do a similar thing, but it’s preferred to use the cron module because there are more examples available in this repository examples
There are multiple tutorials for cron job patterns
Note that the cron job modules have 6 values but the crontab website has 5 values because the first start (second) is optional
The cron format consists of: ``` * * * * * * ┬ ┬ ┬ ┬ ┬ ┬ │ │ │ │ │ │ │ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun) │ │ │ │ └───── month (1 - 12) │ │ │ └────────── day of month (1 - 31) │ │ └─────────────── hour (0 - 23) │ └──────────────────── minute (0 - 59) └───────────────────────── second (0 - 59, OPTIONAL)
1- At 04:05
2- At every 10th minute.
3- Every odd minute
4- At every minute from 10 through 20 on Sunday and Monday.
You know that Node.js is a single thread so using clustering in production, and running Node.js projects on multiple CPUs, to do this you can PM2.
If you use Cron job in Nest.js Framework or Express.js and use clustering so the cron job starts on multiple CPUs. Let’s review an example that shows you the problem.
Cronjob In Cluster Mode
>>> Problem
npm install cron
Run the project based on cluster mode with PM2, the cluster mode allows networked Node.js applications (HTTP(s)/TCP/UDP server) to be scaled across all CPUs available
pm2 start index.js -i max
pm2 logs
As you can see after 20 seconds the cron job has executed the desired function 8 times instead of 2 times, because the project clusters on 4 CPUs
>>> Solution
For solving this problem you should use NODE_APP_INSTANCE environment variable to run a cronjob only on one process,
The result
As you see, cronjob is running just on one process.
If you want to run in different environments with cluster mode and none cluster mode, with the NODE_ENV variable, handle this problem
NODE_ENV=local node index
With these conditions, the cron job runs in the local environment and runs in the prod environment with cluster mode.
When you start a cron job on the server, It runs based on the time server and timezone of the server. the best approach is using the timezone ‘Etc/UTC’ instead of the local timezone server.
>>> Problem
Imagine there is a website and this website publishes new data every day at 8:00 AM o’clock. Your script is running on the server, the problem is that some timezone clocks change (daylight saving time) so when the time of the server changes, The execution time of your script is also affected
>>> Solution
Check the local time from the UTC time
For more information and to develop web applications using Node JS, Hire Node Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop your custom web app using Node JS, please visit our technology page.
Content Source:
Node.js 18.0 is released by the Node.js community. The most wonderful news is that in October 2022, this version will be elevated to long-term support (LTS). The codename for the release will be ‘Hydrogen’ once it is promoted to long-term support. Support for Node.js 18 will last until April 2025.
The most exciting news is that version 18 will finally provide native fetch functionality in Node.js. For the longest time, Node did not contain support for fetch, which is a highly standard API on the web for conducting HTTP requests or any other type of network request, and Node did not support it by default. If you wanted to make an HTTP request, you had to either use third-party tools or write the request from scratch. The implementation comes from undici and is inspired by node-fetch which was originally based upon undici-fetch. The implementation strives to be as close to spec-compliant as possible, but some aspects would require a browser environment and are thus omitted.
The API will remain experimental until further test coverage is introduced and the contributors have verified that the API implements as much of the requirements as is practicable.
Because JavaScript is utilised in so many areas, this is actually wonderful news for the entire ecosystem.It’s utilised on the web, in Node.js, and in Cloudflare workers, for example.
Cloudflare workers are currently shipping with their own proprietary implementation fetch. You’ll ought to install some few packages until you can use Node.There is a version for the web, so there is a lot of inconsistency along the route. Node is now providing formal support for this. That is, any environment that runs JavaScript on servers is almost certainly running Node. If it isn’t running Deno, it will support fetch by default, and because this is the team, the real team, doing it.
If you look at this issue closely, you can see that Node utilised or primarily ported a library called Undici. What exactly is this library? It’s officially produced by the Node team, however it’s really an HTTP 1.1 full-fledged client written entirely in Node JS.
The node:test module facilitates the creation of JavaScript tests that report results in TAP format. To access it:
import test from ‘node:test’;
This module is only available under the node: scheme. __Node Document
Node.js 18 features a test runner that is still in development.It is not meant to replace full-featured alternatives such as Jest or Mocha, but it does provide a quick and straightforward way to execute a test suite without any additional dependencies.
It provides TAP output, which is extensively used, and makes the output easier to consume.
More information may be found in the community blog post and the Node.js API docs
Note: The test runner module is only available using the node: prefix. The node: prefix denotes the loading of a core module. Omitting the prefix and importing ‘test’ would attempt to load a userland module. __Node Documents
As with other major releases, this one upgrades the minimum supported levels for systems and tooling needed to create Node.js. Node.js includes pre-built binaries for a variety of platforms. The minimum toolchains for each major release are evaluated and raised if needed.
Due to issues with creating the V8 dependencies in Node.js, prebuilt binaries for 32-bit Windows will not be accessible at first. With a future V8 upgrade, we hope to restore 32-bit Windows binaries for Node.js 18.
Supported platforms is current as of the branch/release to which it belongs
Node.js relies on V8 and libuv. We adopt a subset of their supported platforms.
There are three support tiers:
The V8 engine has been updated to version 10.1 as part of Chromium 101. The following new features are added in Node.js 17.9.0 over the previous version:
With the findLast() and findLastIndex() methods, This use case is easily and ergonomically solved.They perform identically to their find() and findIndex() equivalents, with the exception that they begin their search at the end of the Array or TypedArray.
For more information and to develop web applications using Node JS, Hire Node Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop your custom web app using Node JS, please visit our technology page.
Content Source:
If you’re building a minimalist product, but want to add an extra level of customisation or expansion, then plugins are a great way to enable that. They allow each instance to be customised with additional code that anyone can create.
In this tutorial, we will extend a minimal web server with a plugin system, create a plugin, and use that plugin with the server. We’ve already created a very basic web server. We’ll use this as our starter code.
But before we start, what is a plugin? A plugin is an extra piece of code that expands what a program can normally do. Web extensions are a good example of this. They leverage existing APIs, and build new functionality upon them. In certain circumstances, they can also be used to patch bugs and flaws that the main software provider has not yet addressed.
In this tutorial, we’ll be building a request counting plugin, and the system to load and unload that plugin.
Let’s start by creating a fresh Node.js project. I’ll be using NPM in this tutorial, but I’ll add the Yarn commands too.
mkdir my-plugin-app
cd my-plugin-app
npm init -y (yarn init -y)
npm i express (yarn add express)
We won’t go through the process of creating an app for our plugins system. Instead, we’ll use this starter code. A simple server with one endpoint. Create an index.js file and add this starter code.
const express = require('express'); const EventEmitter = require('events'); class App extends EventEmitter { constructor() { super(); this.server = express(); this.server.use(express.json()); } start() { this.server.get('/', (req, res) => { res.send('Hello World!'); }); this.server.listen(8080, () => { console.log('Server started on port 3000') this.emit('start'); }); } stop() { if (this.stopped) return; console.log('Server stopped'); this.emit('stop'); this.stopped = true; process.exit(); } } const app = new App(); app.start(); ["exit", "SIGINT", "SIGUSR1", "SIGUSR2", "SIGTERM", "uncaughtException"].forEach(event => { process.on(event, () => app.stop()); });
To get a sense as to what our plugin system will do, let’s create a little plugin containing everything a plugin will need. The type of plugin system we’ll be implementing has two events. load and unload are the two times we will directly call any code in the plugin. load sets up any extra routes, middleware or anything else that is part of the plugin, and unload tells us to safely stop whatever we’re doing and save any persistent data.
This plugin will set up a middleware to count the number of requests we get. In addition, it will add an API route so we can query the number of requests that have been made so far. The plugin will export two different functions, one for each event.
const fs = require('fs'); let count = 0; function load(app) { try { count = +fs.readFileSync('./counter.txt'); } catch (e) { console.log('counter.txt not found. Starting from 0'); } app.server.use((req, res, next) => { count++; next(); }); app.server.get('/count', (req, res) => { res.send({ count }); }) } // Save request count for next time function unload(app) { fs.writeFileSync('./counter.txt', count); } module.exports = { load, unload };
Our plugin system will all be kept in a separate class from the main app, we’ll put this in a new file plugins.js. The point of this class is to load and unload plugins.
The load function takes a path to a plugin file, and uses the require method to load it during runtime. The loadFromConfig method allows us to load plugins defined in a config file.
const fs = require("fs"); class Plugins { constructor(app) { super(); this.app = app; this.plugins = {}; } async loadFromConfig(path='./plugins.json') { const plugins = JSON.parse(fs.readFileSync(path)).plugins; for (let plugin in plugins) { if (plugins[plugin].enabled) { this.load(plugin); } } } async load(plugin) { const path = plugins[plugin]; try { const module = require(path); this.plugins[plugin] = module; await this.plugins[plugin].load(this.app); console.log(`Loaded plugin: '${plugin}'`); } catch (e) { console.log(`Failed to load '${plugin}'`) this.app.stop(); } } } module.exports = Plugins;
We’ll use a plugins.json file to store the paths to all the plugins we wish to load, then call the loadFromConfig method to load them all at once. Put the plugins.json file in the same directory as your code.
{ "counter": "./counter.js" }
Finally, we’ll create an instance of the plugin in our app. Import the Plugins class, create an instance in the constructor, and call loadFromConfig leaving the path blank (the default is ./plugins.json).
const express = require('express'); const Plugins = require('./plugins'); class App { constructor() { super(); this.plugins = new Plugins(this); this.server = express(); this.server.use(express.json()); } async start() { await this.plugins.load(); this.server.get('/', (req, res) => { res.send('Hello World!'); }); this.server.listen(8080, () => { console.log('Server started on port 3000') }); } stop() { if (this.stopped) return; console.log('Server stopped'); this.stopped = true; process.exit(); } } const app = new App(); app.start(); ["exit", "SIGINT", "SIGUSR1", "SIGUSR2", "SIGTERM", "uncaughtException"].forEach(event => { process.on(event, () => app.stop()); });
We now need to handle the unload method exported from our plugin. And once we do, we need to remove it from the plugins collection. We’ll also include a stop method which will unload all plugins. We’ll use this method later to enable safe shutdowns.
const fs = require("fs"); class Plugins { constructor(app) { super(); this.app = app; this.plugins = {}; } async loadFromConfig(path='./plugins.json') { const plugins = JSON.parse(fs.readFileSync(path)).plugins; for (let plugin in plugins) { if (plugins[plugin].enabled) { this.load(plugin); } } } async load(plugin) { const path = plugins[plugin]; try { const module = require(path); this.plugins[plugin] = module; await this.plugins[plugin].load(this.app); console.log(`Loaded plugin: '${plugin}'`); } catch (e) { console.log(`Failed to load '${plugin}'`) this.app.stop(); } } unload(plugin) { if (this.plugins[plugin]) { this.plugins[plugin].unload(); delete this.plugins[plugin]; console.log(`Unloaded plugin: '${plugin}'`); } } stop() { for (let plugin in this.plugins) { this.unload(plugin); } } } module.exports = Plugins;
To make sure that plugins get a chance to unload when the app closes, we need to call Plugins.stop. In the index.js code, we included a stop method that gets called when the app is killed, and we’ve just added a stop method to the Plugins class. So let’s call the Plugins.stop method when our app stop method is called.
Add the following to the App.stop method.
stop() { if (this.stopped) return; + this.plugins.stop(); console.log('Server stopped'); this.stopped = true; process.exit(); }
For more information and to develop web applications using Node JS, Hire Node Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop your custom web app using Node JS, please visit our technology page.
Content Source:
We are excited to announce the release of Node.js 16 today! Highlights include the update of the V8 JavaScript engine to 9.0, prebuilt Apple Silicon binaries, and additional stable APIs.
You can download the latest release from https://nodejs.org/en/download/current/, or use Node Version Manager on UNIX to install with nvm install 16
. The Node.js blog post containing the changelog is available at https://nodejs.org/en/blog/release/v16.0.0.
Initially, Node.js 16 will replace Node.js 15 as our ‘Current’ release line. As per the release schedule, Node.js 16 will be the ‘Current’ release for the next 6 months and then promoted to Long-term Support (LTS) in October 2021. Once promoted to long-term support the release will be designated the codename ‘Gallium’.
As a reminder – Node.js 12 will remain in long-term support until April 2022, and Node.js 14 will remain in long-term support until April 2023. Node.js 10 will go End-of-Life at the end of this month (April 2021). More details on our release plan/schedule can be found in the Node.js Release Working Group repository.
As always a new version of the V8 JavaScript engine brings performance tweaks and improvements as well as keeping Node.js up to date with JavaScript language features. In Node.js v16.0.0, the V8 engine is updated to V8 9.0 — up from V8 8.6 in Node.js 15.
This update brings the ECMAScript RegExp Match Indices, which provide the start and end indices of the captured string. The indices array is available via the .indices
property on match objects when the regular expression has the /d
flag.
> const matchObj = /(Java)(Script)/d.exec('JavaScript'); undefined > matchObj.indices [ [ 0, 10 ], [ 0, 4 ], [ 4, 10 ], groups: undefined ] > matchObj.indices[0]; // Match [ 0, 10 ] > matchObj.indices[1]; // First capture group [ 0, 4 ] > matchObj.indices[2]; // Second capture group [ 4, 10 ]
The Timers Promises API provides an alternative set of timer functions that return Promise objects, removing the need to use util.promisify()
.
import { setTimeout } from 'timers/promises'; async function run() { await setTimeout(5000); console.log('Hello, World!'); } run();
Added in Node.js v15.0.0 by James Snell (https://github.com/nodejs/node/pull/33950), in this release, they graduate from experimental status to stable.
The nature of our release process means that new features are released in the ‘Current’ release line approximately every two weeks. For this reason, many recent additions have already been made available in the most recent Node.js 15 releases, but are still relatively new to the runtime.
Some of the recently released features in Node.js 15, which will also be available in Node.js 16, include:
AbortController
implementation based on the AbortController Web API(buffer.atob(data))
and btoa (buffer.btoa(data))
implementations for compatibility with legacy web platform APIsNode.js provides pre-built binaries for several different platforms. For each major release, the minimum toolchains are assessed and raised where appropriate.
Node.js v16.0.0 will be the first release where we ship prebuilt binaries for Apple Silicon. While we’ll be providing separate tarballs for the Intel (darwin-x64)
and ARM (darwin-arm64)
architectures the macOS installer (.pkg)
will be shipped as a ‘fat’ (multi-architecture) binary.
The production of these binaries was made possible thanks to the generosity of MacStadium donating the necessary hardware to the project.
On our Linux-based platforms, the minimum GCC level for building Node.js 16 will be GCC 8.3. Details about the supported toolchains and compilers are documented in the Node.js BUILDING.md file.
As a new major release, it’s also the time where we introduce new runtime deprecations. The Node.js project aims to minimize the disruption to the ecosystem for any breaking changes. The project uses a tool named CITGM (Canary in the Goldmine), to test the impact of any breaking changes (including deprecations) on a large number of the popular ecosystem modules to provide additional insight before landing these changes.
Notable deprecations in Node.js 16 include the runtime deprecation of access to process.binding()
for a number of the core modules, such as process.binding('http_parser')
.
For more information and to develop web applications using Node JS, Hire Node Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using Node JS, please visit our Hire Node Developer technology page.
Content Source:
In this blog, we’ll make a comparative analysis of Golang vs. Node.js for backend web development.
Now, we want to understand whether the switch from a traditional Node.js to the popular Golang is sensible or not. That’s why we would like to compare the two solutions to help you make the best choice.
Even though Golang was only launched in 2009, it can still be regarded as quite mature and robust.
However, there can be no comparison when Node.js comes into play. It has a broader audience which supports the platform, even though the API is changing somewhat.
Being an interpreted language, which is based on JavaScript, Node.js turns out to be a bit slower than other compiled languages. Node.js is not able to provide the raw performance of CPU or memory-bound tasks that Go does. This is because it’s based on C and C++, which are initially good in terms of performance.
However, when it comes to real life, both show almost equal results.
Node.js is single-threaded and uses an event-callback mechanism. This is what makes Node.js much weaker than Go. It uses co-routines (called “goroutines”) and a lightweight thread, communication among which is elegant and seamless due to channels.
Node.js is much weaker in terms of parallel processes for big projects compared to Golang, which was specifically designed to overcome possible issues in this area. Golang has the advantage due to goroutines that enable multiple threads to be performed concurrently, with parallel tasks executed simply and safely.
Front-End and Back-End
You should keep in mind that Golang is perfect for server-side applications, while Node.js is unrivaled when it comes to client-side development. Therefore, Go is an ideal decision if you want to create high-performing concurrent services on the back-end. And Node.js is your choice for the front-end.
For a long time, Golang was regarded as having a very small community because it was young and not widely implemented. Now, the situation has changed. Despite the fact that Go still fails to keep pace with Node.js support, the language boasts numerous packages (more than 100), and the number keeps growing.With JavaScript, you’ll have no difficulty in finding the right tool or package for your project; today, there are more than 100,000. Hundreds of libraries, various tutorials, and multiple platforms are at your disposal.
According to the 2017 Developer Survey by StackOverflow, JavaScript continues to occupy the leading position, being chosen by 61.2% of developers. Go showed a slightly worse result 4.3%. However, this means Go is already among the most promising languages of 2018, based even on simple Google search.
Currently, it’s still much easier to find a competent team of Node.js developers than put together one of Golang specialists. However, you can always take the IT outsourcing route and reach out to a reputable team with a strong portfolio of Go work.
When you deal with errors while using Go, you have to implement explicit error checking. This can make the process of finding the causes of errors difficult. Yet numerous developers argue that such an approach provides a cleaner application in general.
The Node.js approach with a throw/catch mechanism is more traditional and is preferred by many developers, although there are some problems with consistency at the end.
JavaScript is one of the most common coding languages nowadays. If you’re familiar with it, it will be no big deal to adapt to using Node.js programming. If you’re a newbie in JavaScript, you can leverage JavaScript’s vast community, which is always ready to share its expertise or give advice.
With Golang, you have to be ready to learn a new language, including co-routines, strict typing, pointers, and other programming concepts that may confuse you at first.
The latest trend of 2017 is blockchain technology. Many projects nowadays trumpet their blockchain-based application at every opportunity. And for good reason! The technology provides reliability, full control for the user, high-quality data, longevity, process integrity, transparency, and one more pack of buzzwords that define the viability of many startups today.
Theoretically, it’s possible to implement Node.js for developing a blockchain. However, building a blockchain in Go is a much easier solution and we highly recommend it.
In its essence, a blockchain is a distributed database of records. Go implies the implementation of an array and a map. The array keeps ordered hashes, and the map would keep hash -> blockpairs (maps are unordered). Then, we add blocks, and that’s it!
So, what should you choose: Node.js or Golang? The answer to this question depends on which type of development you need at the moment and how much you are going to scale the project.
For sure, Node.js has a broader community and a comprehensive documentation, yet, Go has a syntactically cleaner concurrency model, and it is better suited for scaling up.
Node.js, in its turn, can offer you a variety of packages, most of which are hard to re-implement in Go. In these case, it would be wiser to use Node.js.
If you feel overwhelmed by all this information or simply need some extra hands with Golang or Node.js expertise, then write a comment to initialise a conversation with other developers here.
For more information and to develop web application using Node JS, Hire Node Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using Node JS, please visit our Hire Node Developer technology page.
Content Source:
In this article, we’re going to discuss about Node.js 15 new features, including throw on unhandled rejections and V8 8.6 language features.
Node.js 15 was released recently. It comes with a number of major features:
Let’s explore what they are and how to use them.
In a previous article, we provided instructions on using NVM (Node Version Manager) to manage Node.js and NPM versions. In our environment, we had Node.js 12.16.0 and NPM 6.14.8 installed. By running nvm install node, we installed Node.js 15.4.0 and NPM7.0.15.
We have two windows open, one is set to Node.js 12, and the other one is set to Node.js 15.
On the node12 window:
$ nvm use 12 Now using node v12.16.0 (npm v6.14.8)
On the node15 window:
$ nvm use 15 Now using node v15.4.0 (npm v7.0.15)
Now we’re ready to explore.
The unhandledRejection event is emitted whenever a promise is rejected and no error handler is attached to the promise within a turn of the event loop. Starting from Node.js 15, the default mode for unhandledRejection has been changed to throw from warn. In throw mode, if an unhandledRejection hook is not set, the unhandledRejection is raised as an uncaught exception.
Create a program so that a promise is rejected with an error message:
function myPromise() { new Promise((_, reject) => setTimeout( () => reject({ error: 'The call is rejected with an error', }), 1000 ) ).then((data) => console.log(data.data)); } myPromise();
When you run this code on node12 window it shows a long warning message:
$ node myPromise.js (node:79104) UnhandledPromiseRejectionWarning: #<Object> (node:79104) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:79104) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.Users that have an unhandledRejection hook should see no change in behavior, and it’s still possible to switch modes using the --unhandled-rejections=mode process flag.
Run this code on the node15 window and it throws the error, UnhandledPromiseRejection
:
$ node myPromise.js node:internal/process/promises:227 triggerUncaughtException(err, true /* fromPromise */); ^ [UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "#<Object>".] { code: 'ERR_UNHANDLED_REJECTION' }
Add an error handler in the then clause in the below code (.catch((error) => console.log(error.error)) works too).
function myPromise() { new Promise((_, reject) => setTimeout( () => reject({ error: 'The call is rejected with an error', }), 1000 ) ).then( (data) => console.log(data.data), (error) => console.log(error.error) ); } myPromise();
Now, the code runs correctly on both node12 and node15 windows:
$ node myPromise.js The call is rejected with an error
It’s best practice to write an error handler for promises. However, there will be cases where errors are not caught. It’s a good idea to set up the unhandledRejection hook to catch potential errors.
function myPromise() { new Promise((_, reject) => setTimeout( () => reject({ error: 'The call is rejected with an error', }), 1000 ) ).then((data) => console.log(data.data)); } myPromise(); process.on('unhandledRejection', (reason, promise) => { console.log('reason is', reason); console.log('promise is', promise); // Application specific logging, throwing an error, or other logic here });
The unhandledRejection hook works for both Node.js 12 and Node.js 15. With that set up, unhandledRejection can be handled properly.
$ node myPromise.js reason is { error: 'The call is rejected with an error' } promise is Promise { <rejected> { error: 'The call is rejected with an error' } }
The V8 JavaScript engine has been updated from 8.4 to 8.6. Along with performance tweaks and improvements, the V8 update also brings the following language features:
First, let’s take a look at the existing Promise.all() method.
Promise.all() takes an iterable of promises as an input and returns a single promise that resolves to an array of the results of the input promises.
The following program calls Promise.all() on two resolved promises:
function myPromise(delay) { return new Promise((resolve) => setTimeout( () => resolve({ data: `The data from ${delay} ms delay`, }), delay ) ); } async function getData() { try { const data = await Promise.all([myPromise(5000), myPromise(100)]); console.log(data); } catch (error) { console.log(error); } } getData();
The Promise.all() returned promise will resolve when all of the input’s promises have resolved, or if the input iterable contains no promises:
$ node myPromise.js [ { data: 'The data from 5000 ms delay' }, { data: 'The data from 100 ms delay' } ]
The following program calls Promise.all() on two rejected promises.
function myPromise(delay) { return new Promise((_, reject) => setTimeout( () => reject({ error: `The error from ${delay} ms delay`, }), delay ) ); } async function getData() { try { const data = await Promise.all([myPromise(5000), myPromise(100)]); console.log(data); } catch (error) { console.log(error); } } getData();
Promise.all() immediately rejects any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message or error:
$ node myPromise.js { error: 'The error from 100 ms delay' }
Promise.any() is new in Node.js 15. This is the opposite of Promise.all(). It takes an iterable of promises and, as soon as one of the promises in the iterable fulfills, returns a single promise that resolves with the value from that promise.
The following program calls Promise.any() on two resolved promises:
function myPromise(delay) { return new Promise((resolve) => setTimeout( () => resolve({ data: `The error from ${delay} ms delay`, }), delay ) ); } async function getData() { try { const data = await Promise.any([myPromise(5000), myPromise(100)]); console.log(data); } catch (error) { console.log(error); console.log(error.errors); } } getData();
Promise.any() returns the first resolved promise:
$ node myPromise.js { data: 'The error from 100 ms delay' }
The following program calls Promise.any() on two rejected promises:
function myPromise(delay) { return new Promise((_, reject) => setTimeout( () => reject({ error: `The error from ${delay} ms delay`, }), delay ) ); } async function getData() { try { const data = await Promise.any([myPromise(5000), myPromise(100)]); console.log(data); } catch (error) { console.log(error); console.log(error.errors); } } getData();
If no promises in the iterable are fulfilled — i.e. all of the given promises are rejected — the returned promise is rejected with an AggregateError, a new subclass of Error that groups together individual errors.
$ node myPromise.js [AggregateError: All promises were rejected] [ { error: 'The error from 5000 ms delay' }, { error: 'The error from 100 ms delay' } ]
In the previous examples, we used setTimeout inside the promise call. The WindowOrWorkerGlobalScope’s setTimeout uses a callback. However, timers/promises provides a promisified version of setTimeout, which can be used with async/await.
const { setTimeout } = require('timers/promises'); async function myPromise(delay) { await setTimeout(delay); return new Promise((resolve) => { resolve({ data: `The data from ${delay} ms delay`, }); }); } async function getData() { try { const data = await Promise.any([myPromise(5000), myPromise(100)]); console.log(data); } catch (error) { console.log(error); console.log(error.errors); } } getData();
AbortController is a JavaScript object that allows us to abort one or more web requests as and when desired. We gave examples of how to use AbortController on the topic of useAsync.
Both await setTimeout and AbortController are experimental features.
First, let’s take a look at the existing String.prototype.replace() method.
replace() returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a regular expression. The replacement can be a string or a function to be called for each match.
If the pattern is a string, only the first occurrence will be replaced.
'20+1+2+3'.replace('+', '-');
Executing the above statement will yield “20–1+2+3”.
In order to replace all ‘+’ with ‘-’, a regular expression has to be used.
'20+1+2+3'.replace(/\+/g, '-');
Execute the above statement will yield “20–1-2-3”.
replaceAll() is new in Node.js 15 to avoid using the regular expression. It returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a regular expression and the replacement can be a string or a function to be called for each match.
With replaceAll(), we do not have to use a regular expression to replace all ‘+’ with ‘-’.
'20+1+2+3'.replaceAll('+', '-');
Executing the above statement will yield “20–1-2-3”.
Logical assignment operators &&=, ||=, and ??=
A few logical assignment operators have been added to Node.js 15.
The logical AND assignment (x &&= y) operator only assigns if x is truthy. x &&= y is equivalent to x && (x = y), and it is not equivalent to x = x && y.
let x = 0; let y = 1; x &&= 0; // 0 x &&= 1; // 0 y &&= 1; // 1 y &&= 0; // 0
The logical OR assignment (x ||= y) operator only assigns if x is falsy. x ||= y is equivalent to x || (x = y), and it is not equivalent to x = x || y.
let x = 0; let y = 1; x ||= 0; // 0 x ||= 1; // 1 y ||= 1; // 1 y ||= 0; // 1
The logical nullish assignment (x ??= y) operator only assigns if x is nullish (null or undefined). x ??= y is equivalent to x ?? (x = y), and it is not equivalent to x = x ?? y.
let x = undefined; let y = ''; x ??= null; // null x ??= 'a value'; // "a value" y ??= undefined; // "" y ??= null; // ""
For more information and to develop web application using Node JS, Hire Node Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using Node JS, please visit our Hire Node Developer technology page.
Content Source:
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
© 2025 — HK Infosoft. All Rights Reserved.
© 2025 — HK Infosoft. All Rights Reserved.
T&C | Privacy Policy | Sitemap