Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - Easiest way to run code in a different process

What is the easiest way to run some code (not command!) in a different process and communicate its result with the main process?

So I have a quite intensive task that needs to be split up into different processes. What's the easiest way to do something like this?

// in main process
var otherProcess = createAnotherProcess(function() {
    console.log("this code is ran in another process");
    return "some data";
});
otherProcess.on("done", function(data) {
    console.log(data); // will output "some data"
});

Having a single source code file that is able to run code in multiple processes would be amazing! Is this even possible? I've tried reading a bit about "child_processes" in node but find it a little too convoluted.

Any help?

like image 452
Luca Matteis Avatar asked Oct 19 '11 13:10

Luca Matteis


People also ask

Could we run an external process with node js?

To execute an external program from within Node. js, we can use the child_process module's exec method. const { exec } = require('child_process'); exec(command, (error, stdout, stderr) => { console.


2 Answers

var spawn = require("child_process").spawn;
var stat = spawn("dstat", ["-r", "--noheaders", "--nocolor"]);


var output = function (output_data) {
  //do something with output_data
};

stat.stdout.on("data", output);

http://nodejs.org/docs/v0.4.11/api/child_processes.html

like image 72
chovy Avatar answered Oct 23 '22 18:10

chovy


To run some command in child process you can use child_process.spawn method.

If you want to run some heavy JS code you can split it execution to chunks to not block the IO using process.nextTick.

like image 28
bjornd Avatar answered Oct 23 '22 19:10

bjornd