Many people seem unable to understand how single-threaded NodeJS can compete with multi-threaded backends.

To find out why, we need to understand what Node.js really means by being single-threaded.

JavaScript itself was originally created to do simple things like validating forms, making responses, etc. It wasn’t until 2009 that Ryan Dahl, creator of Node.js, made it possible to write server-side code in JavaScript.

Server-side languages that support multithreading have various constructs and constructs for synchronization between threads and other thread-oriented features.

Supporting these things means that JavaScript needs to change the entire language, which goes against the ideas of the creators of JavaScript. So, in order for pure JavaScript to support multithreading, Dahl had to create a solution. 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 helper threads in the worker thread pool.

Event-looping Node.js’s mechanism for handling non-blocking I/O operations — even though JavaScript is single-threaded — shifts operations to the system kernel when possible. When a JavaScript operation blocks a thread, the event loop also blocks.

A working pool is an execution model that generates and processes individual threads, then synchronously executes tasks and returns the results to an event loop. The event loop then performs the provided callback using the result.

Basically, the working pool handles asynchronous I/O operations — primarily interactions with system disks and networks. Some modules use out-of-the-box working pools, such as FS (I/O-heavy) or Crypto (CPU-heavy). Working pooling is implemented in libuv, which causes a slight but negligible delay when Node needs to transfer data internally between JavaScript and C++.

Now that we understand the meaning of event loops and working pools, let’s look at the following code:

In the above code, we don’t have to wait for events synchronously. We delegate reading the file to the working pool and use the result to call the provided function. Because the working pool has its own threads, the event loop can continue to execute normally while reading the file.


To introduce you: Worker_Threads

With the release of Node.js 10.5.0 came worker_Threads. It supports the creation of simple multithreaded applications in JavaScript

Worker_threads is a NodeJS module package. A thread worker is a piece of code that is generated in a separate thread (usually pulled from a file).

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 do heavy tasks without interfering with 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 the thread, 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' });

Copy the code

File name: 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));

Copy the code

Output:

This article is participating in node.js advanced technology essay, click to see more details