Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS: will this code run multi-core or not?

Tags:

node.js

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.

like image 276
Claudio Avatar asked Sep 01 '11 09:09

Claudio


People also ask

Does node JS run on multiple cores?

Node. js absolutely does scale on multi-core machines. Yes, Node. js is one-thread-per-process.

How many cores does node js use?

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.

Is NodeJS multithreaded?

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.

How do you tell if a program is using multiple cores?

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.


1 Answers

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...)

like image 97
Morten Siebuhr Avatar answered Oct 17 '22 16:10

Morten Siebuhr