MOCKSTACKS
EN
Questions And Answers

More Tutorials









NodeJS Cluster Module

Hello World


This is your cluster.js:

const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
 // Fork workers.
 for (let i = 0; i < numCPUs; i++) {
 cluster.fork();
 }
 cluster.on('exit', (worker, code, signal) => {
 console.log(`worker ${worker.process.pid} died`);
 });
} else {
 // Workers can share any TCP connection
 // In this case it is an HTTP server
 require('./server.js')();
}

This is your main server.js:

const http = require('http');
function startServer() {
 const server = http.createServer((req, res) => {
 res.writeHead(200);
 res.end('Hello Http');
 });
 server.listen(3000);
}
if(!module.parent) {
 // Start server if file is run directly
 startServer();
} else {
 // Export server, if file is referenced via cluster
 module.exports = startServer;
}

In this example, we host a basic web server, however, we spin up workers (child processes) using the built-in cluster module. The number of processes forker depend on the number of CPU cores available. This enables a Node.js application to take advantage of multi-core CPUs, since a single instance of Node.js runs in a single thread. The application will now share the port 8000 across all the processes. Loads will automatically be distributed between workers using the Round-Robin method by default.

Conclusion

In this page (written and validated by ) you learned about NodeJS Cluster Module . What's Next? If you are interested in completing NodeJS tutorial, your next topic will be learning about: NodeJS Readline.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.