A lot of people can't seem to understand how single-threaded NodeJS can compete with multi-threaded backends.
To find out why, we have to understand what it really means that Nodejs is single-threaded.
JavaScript itself was originally created to do simple things like validate forms, make responses, etc. It wasn't until 2009 that Node.js creator Ryan Dahl made it possible to write server-side code using JavaScript.
Server-side languages that support multithreading have various structures and constructs for synchronizing between threads and other thread-oriented features.
Supporting these things would mean that JavaScript would need to change the entire language, which goes against the ideas of JavaScript's creators. Therefore, in order to support multi-threading in pure JavaScript, Dahl had to create a workaround. Let’s take a look!
How does Node.js work?
Node.js uses two kinds of threads: the main thread, which is handled by the event loop, and several secondary threads in a pool of worker threads.
Event Loop Node.js's mechanism for handling non-blocking I/O operations—even though JavaScript is single-threaded—offloads operations to the system kernel when possible. When a JavaScript operation blocks a thread, the event loop is also blocked.
A worker pool is an execution model that spawns and processes separate threads, then executes tasks synchronously and returns the results to the event loop. The event loop then uses said result to execute the provided callback.
Basically, the worker pool handles asynchronous I/O operations - primarily interactions with the system disk and network. Some modules use worker pools out of the box, such as fs (I/O-heavy) or crypto (CPU-heavy). The worker pool is implemented in libuv, which causes a slight but almost negligible delay when Node needs to transfer data internally between JavaScript and C++.
After understanding the meaning of event loop and work pool, let's look at the following code:
In the above code, we don't have to wait for the event synchronously. We delegate the task of reading the file to the worker pool and call the provided function with the result. Since the worker pool has its own thread, the event loop can continue executing normally while reading the file.
Let me introduce to you: worker_threads
With the release of Node.js 10.5.0, worker_threads appeared. It supports creating simple multi-threaded applications in JavaScript
worker_threads is a nodejs module package. A thread worker is a piece of code (usually taken from a file) generated in a separate thread.
It is important to note that the terms thread worker, worker, and thread are often used interchangeably. They all refer to the same thing.
Worker threads in Node.js are useful for performing heavy JavaScript tasks. With the help of threads, Workers can easily run JavaScript code in parallel, making it faster and more efficient. We can complete heavy tasks without disturbing the main thread.
Worker threads were not introduced in older versions of Node.js. So first update your Node.js to get started.
Now create two files to implement threads as follows:
File name: worker.js
const { workerData, parentPort } = require('worker_threads'); console.log(`Write-up on how ${workerData} wants to chill with the big boys`); parentPort.postMessage({ filename: workerData, status: 'Done' });
Filename: index.js
const { Worker } = require('worker_threads'); const runSerice = (workerData) => { return new Promise((resolve, reject) => { const worker = new Worker('./worker.js', { workerData }); worker.on('message', resolve); worker.on('error', reject); worker.on('exit', (code) => { if (code !== 0) reject(new Error(`Worker Thread stopped with exit code ${code}`)); }); }); }; const run = async () => { const result = await runSerice('Tunde Ednut'); console.log(result); }; run().catch((err) => console.error(err));
Output: