0

Say my pc has a cpu with 2 cores, and my node.js application using express. How can i run this application on 1 core and this same application on the other core?

Chanlito
  • 2,322
  • 2
  • 17
  • 27

2 Answers2

0

Nicovank is right. You are interested in feature called cluster. In nodejs you getting number of cores by this code:

const numCPUs = require('os').cpus().length;

Please refer to this section of documentation: https://nodejs.org/dist/latest-v7.x/docs/api/cluster.html#cluster_cluster. The have great examples.

Sergey Yarotskiy
  • 4,536
  • 2
  • 19
  • 27
0

Here's a basic example of an express server running in multiple cores using the cluster module.

const cluster = require('cluster');
//Get number of CPUs
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  // Fork one worker per core.
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
  });

} else {
    //Worker code...

    const express = require('express');
    const app = express();

    app.get('/', function (req, res) {
        res.send('Hello World!');
    });

    // Bind to a port
    app.listen(8080, () => {
        console.log(`[PID=${process.pid}] server started!`);
    });

}

There are some third party modules too:

You can also check:

Node.js on multi-core machines

Community
  • 1
  • 1
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98