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?
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With