node.js run function in child process?

15,125

Just seen that node.js provides the 'fork' function, for executing modules, though they will need to be written as if they were expecting command line arguments, processing the process.argv array.

The command call being:

child_process.fork(modulePath[, args][, options])

More details here.

In my specific case forking probably doesn't make sense, since there is already a fork being made by the node.js library I am using.

Share:
15,125
Andre M
Author by

Andre M

Updated on June 13, 2022

Comments

  • Andre M
    Andre M almost 2 years

    I have a node.js application that receives a file, via a web request and then will apply a conversion process to this file. Since the task is long running this needs to run separate to the main thread.

    At the moment I have just called the necessary code via a setTimeout() call. To isolate the main application from the conversion process I would like to move it out into a child process, since it is long running and I would like to isolate the main code from the work being done (am I worrying too much?). At the moment I am calling:

    const execFile = require('child_process').execFile;
    const child = execFile('node', './myModule.js', (error, stdout, stderr) => {
      if (error) {
        throw error;
      }
      console.log(stdout);
    });
    

    Is this the right approach in node.js, or is there of simply starting a child process with the module and params specified, but not have to specify 'node' as the executable?

  • narruc
    narruc over 7 years
    Is each separate message completely isolated from another? i.e. if I send two messages to a child process fork, will they run completely independent of each other?
  • Abdellah Alaoui
    Abdellah Alaoui about 3 years
    yes, I've just tested that. And global variables like global.window don't get shared