12

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?

Andre M
  • 6,649
  • 7
  • 52
  • 93
  • Do you have a particular problem with this approach? That's one of several ways to start a new process (`.spawn()` and `.exec()` are similar). I can tell you that your `throw error` does nothing useful since throwing in a regular async callback can't be caught anywhere useful so it does nothing different than `return`. – jfriend00 Apr 25 '16 at 20:44
  • Is your long-running process CPU-bound, or IO-bound? The answer to that question is very important in determining what approach to use. – JLRishe Apr 25 '16 at 20:47
  • I had based the above code on an example I had. I was hoping to avoid having to explicit reference to the 'node' command, but if that is not seen as a problem then I am fine. As for CPU/IO, it is a video conversion process, so likely a bit of both. Though, I am now seeing the video conversion process is actually spawning an external process (ffmpeg) under the hood, so I might not need to worry about forking (I had thought it was using a library). – Andre M Apr 25 '16 at 21:04
  • @AndreM: hi, may I know how we should show the result in UI in this example? can you look at my question? https://stackoverflow.com/questions/53694567/how-to-show-async-data-in-ui – Amir Dec 09 '18 at 18:28

1 Answers1

3

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.

Andre M
  • 6,649
  • 7
  • 52
  • 93