Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Web Workers in NodeJS?

Anyone knows what the status of Web Worker support in NodeJS is? I found a two year old implementation, node-webworkers, but it didn't run with the current build of NodeJS.

like image 842
Andreas Selenwall Avatar asked Jan 25 '13 13:01

Andreas Selenwall


People also ask

What is html5 web worker?

A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

What are workers in node JS?

Worker Threads in Node. js is useful for performing heavy JavaScript tasks. With the help of threads, Worker makes it easy to run javascript codes in parallel making it much faster and efficient. We can do heavy tasks without even disturbing the main thread.

How many web workers can run concurrently JavaScript?

How many web workers can run concurrently JavaScript? A web worker is a JavaScript program running on a different thread, in parallel with main thread. The browser creates one thread per tab. The main thread can spawn an unlimited number of web workers, until the user's system resources are fully consumed.

Which JavaScript method is used to instantiate a web worker?

You need to use the postMessage() method in the onmessage event handler in worker. js : // src/worker. js onmessage = e => { const message = e.


2 Answers

Now there is https://github.com/audreyt/node-webworker-threads which appears to be actively maintained.

like image 144
We Are All Monica Avatar answered Sep 27 '22 20:09

We Are All Monica


Worker Threads reached stable status in 12 LTS. Usage example

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));
}
like image 42
serv-inc Avatar answered Sep 27 '22 20:09

serv-inc