Worker Threads in Node.js

As defined in the node.js website worker_threads are modules that enable the use of threads that execute JavaScript in parallel. To access worker_thread add require it in your Node.js application as shown below.

const worker = require('worker_threads');
Worker threads are helpful in performing CPU-intensive JavaScript operations. They are not of much help in I/O intensive work. Worker_threads can also share memory whereas child_process or cluster cannot share memory. They share memory by transferring ArrayBuffer instances or by sharing SharedArrayBuffer instances. Let’s look at an example of worker_thread usage.
const {
  Worker, isMainThread, parentPort, workerData
} = require('worker_threads');

if (isMainThread) {
  module.exports = function parseJSAsync(script) {
    return new Promise((resolve, reject) => {
      const worker = new Worker(__filename, {
        workerData: script
      });
      worker.on('message', resolve);
      worker.on('error', reject);
      worker.on('exit', (code) => {
        if (code !== 0)
          reject(new Error(`Worker stopped with exit code ${code}`));
      });
    });
  };
} else {
  const { parse } = require('some-js-parsing-library');
  const script = workerData;
  parentPort.postMessage(parse(script));
}
Our example generates a worker thread for each parse() call. Use the AsyncResource API to inform diagnostic tools about the correlation between tasks and their outputs when you implement a worker pool. By default the worker threads inherit non-process-specific options. You can customize these options like argv and execArgv using worker constructor options.