NodeJS: will this code work multicore or not?

I use this node script as a "runner" for my project (I need to start / stop three scripts at the same time). Now I am wondering if the child_process from the node process will use or not use several cores that my server will have (I'm 90% sure of YES, but better safe than sorry).

var CP = require("child_process") , children = [ 'server1', 'server2', 'server3' ] , child children.forEach(function(name) { child = CP.spawn("node", [name] ) child.stdout.on('data', function (data) { process.stdout.write(data.toString()); }) child.stderr.on('data', function (data) { process.stdout.write(data.toString()); }) } }); 

OS - Ubuntu Linux.

+6
source share
2 answers

Yeah. spawn() creates completely new processes at the OS level.

And you can simplify it a bit using pipe() :

 var spawn = require("child_process").spawn , children = [ 'server1', 'server2', 'server3' ] , child children.forEach(function(name) { child = spawn("node", [name] ) child.stdout.pipe(process.stdout); child.stderr.pipe(process.stderr); // Catch errors (dies quite hard on first child with non-zero exit code...) child.on('exit', function (code) { if(code !== 0) { process.exit(code); } }); }); 

(An exit listener has also been added, so it will somehow propagate errors. If this is something you want to do, you can track them until the last process is complete, and then call process.exit() with the most big or smallest code ...)

+7
source

This will absolutely use multiple cores. Node will not, and should never, associate a child process with a particular processor or CPU core.

0
source

Source: https://habr.com/ru/post/896389/


All Articles