I'm using this node script as a "runner" for my project (need to start/stop three scripts at the same time). Now I wonder if the child_process's spawn from inside a node process will or won't use multi cores that my server would have (I'm 90% confident on a 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 is Ubuntu Linux.
Node. js absolutely does scale on multi-core machines. Yes, Node. js is one-thread-per-process.
Javascript is a single threaded language, therefore one call stack and one memory heap. NodeJS uses Javascript to develop server side applications and shares the same behavior. It runs on one CPU core regardless of how many CPU cores you have in your machine or a virtual machine in the cloud.
Node. js runs JavaScript code in a single thread, which means that your code can only do one task at a time. However, Node. js itself is multithreaded and provides hidden threads through the libuv library, which handles I/O operations like reading files from a disk or network requests.
The easiest way is to open the CPU display in task manager and then right click on the graph. Make sure the display is set to "Logical Processors". Then run your program. See how many of the CPUs are busy.
Yup. spawn()
creates completely new processes on the OS-level.
And you could even simplify it a bit by 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);
}
});
});
(Also added listener on exit
, so it'll at least propagate errors in some way. If it's something you want to do, you may want to keep track of them until the last process has finished, and then call process.exit()
with the largest or smallest code...)
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