Search code examples
javascriptnode.jsmultithreadingchild-processworker

How to call a function in a other thread


I have on my code a heavy algorithm in a function in node.js.

I want to called this function on a other thread to save performances. I have tried :

let ChildProcess = require('child_process');
const thread1 = ChildProcess.spawn(function ()
{
  reloadData();
});

function reloadData() { /* code */ }

But it don't working. I want to called this function on the current .js file, not in a other .js file Thank you !


Solution

  • You can't find the example you're looking for because that's not how any of the child_process functions work. You can't do what you're trying to do.

    You need to put your other functions in a NEW node.js program and then you use the child_process module to run that other program.

    You can then use various different forms to communicate between the two processes such as stdio or tcp networking.

    You also aren't using the arguments to spawn() correctly. If you look at the first argument in the doc, that first argument is a command or another program to run in your local system. It's not some piece of local Javascript.

    Note: This answer was originally written in 2017. Nodejs now has WorkerThreads which you can read about how to use here.