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?
Asked
Active
Viewed 137 times
2 Answers
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:
- Cluster2
- PM2 (Node process manager that has cluster mode)
- StrongLoop - strong-cluster-control
You can also check:

Community
- 1
- 1

Marcos Casagrande
- 37,983
- 8
- 84
- 98