Node.js: Run your code on multiple CPU cores
This documentation is part of the Getting started guide. View the full guide here: Learn how to deploy a Node.js service on Stackhero quickly and securely.
👋 Welcome to the Stackhero documentation!
Stackhero offers a ready-to-use Node.js cloud solution that provides a host of benefits, including:
- Deploy your application in seconds with a simple
git push.- Use your own domain name and benefit from the automatic configuration of HTTPS certificates for enhanced security.
- Enjoy peace of mind with automatic backups, one-click updates, and straightforward, transparent, and predictable pricing.
- Get optimal performance and robust security thanks to a private and dedicated VM.
Save time and simplify your life: it only takes 5 minutes to try Stackhero's Node.js cloud hosting solution!
By default, Node.js uses a single core and one thread. To take advantage of all available CPU cores, you might want to use the Node.js cluster API. You can find the official documentation here: https://nodejs.org/api/cluster.html.
Here is a simple example that creates an HTTP server using all available CPUs:
const cluster = require('cluster');
const http = require('http');
const cpusCount = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers
for (let i = 0; i < cpusCount; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
});
} else {
// Workers share any TCP connection, in this case, an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}