Search code examples
node.jsmultithreadingnwjsworker-thread

worker thread won't respond after first message?


I'm making a server script and, to make it easier for both hosts and clients to do what they want, I made a customizable server script that runs using nw.js(with a visual interface). Said script was made using web workers since nw.js was having problems with support to worker threads.

Now that NW.js fixed their problems with worker threads, I've been trying to move all the things that were inside the web workers to worker threads, but there's a problem: When the main thread receives the answer from the second thread, the later stops responding to any subsequent message.

For example, running the following code with either NW.js or Node.js itself will return "pong" only once

const { Worker } = require('worker_threads');

const worker = new Worker('const { parentPort } = require("worker_threads");parentPort.once("message",message => parentPort.postMessage({ pong: message }));  ', { eval: true });
worker.on('message', message => console.log(message));      
worker.postMessage('ping');
worker.postMessage('ping');

How do I configure the worker so it will keep responding to whatever message it receives after the first one?


Solution

  • Because you use EventEmitter.once() method. According to the documentation this method does the next:

    Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.

    If you need your worker to process more than one event then use EventEmitter.on()

    const worker = new Worker('const { parentPort } = require("worker_threads");' +
       'parentPort.on("message",message => parentPort.postMessage({ pong: message }));',
       { eval: true });