7

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?

1

4 Answers 4

5
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

Sign up to request clarification or add additional context in comments.

1 Comment

So I cannot keep a single source code file? I need to split it into another .js file and call it using spawn("node myfile.js")?
2

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.

1 Comment

Thank you for the asnwer. The process.spawn and siminal methods are focused on exectuing of command, not JavaScript code as question author asked. May I ask you to add some example with executing of JavaScript code, not commands?
1

Use dimas-parallel (on npm):

var dimas = require('dimas-parallel');

dimas.execute(function() {
  // do some stuff on another process
});

Comments

0

You can use node -e <code>

Example:

const { spawn } = require('child_process')

const child = spawn('node', ['-e', 'console.log("in other process", process.pid)'])

child.stdout.on('data', data => {
    console.log(data.toString())
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.