javascript - How to create master node in node.js -
i'm new cluster/child_process modules in node.js. can let me know how can create master node or how make node master?
most of tutorials mention how verify if node master or worker (below code), not how create master.
edit:
var cluster = require('cluster'); var http = require('http'); var numcpus = require('os').cpus().length; if (cluster.ismaster) { // fork workers. (var = 0; < numcpus; i++) { cluster.fork(); } cluster.on('exit', function(worker, code, signal) { console.log('worker ' + worker.process.pid + ' died'); //cluster.fork(); ----------(2) }); } else { // workers can share tcp connection // in case http server //cluster.fork();-----------(1) http.createserver(function(req, res) { res.writehead(200); console.log("hello worldd"); res.end("hello worldd\n"); }).listen(8000); }
edit: how can create proper child process runs continuously. if create new process using cluster.fork (1) in above code, worker processes getting created , destroyed immediately. if create workers (2) in above code, go infinite loop of process death , creation. if above example not clear, please provide code or link demonstrates proper working example of creating child process , processing multiple requests across different processes concurrently. lot.
you don't create master. when call cluster.fork
, creates child process. master still exists. both child , master operate on same code base, , distinguished based on cluster.ismaster
.
edit:
if want create service/webserver on port 8000
. should showed in (2). except, case, go in infinite loop because doing on 'exit' event without checking why 'exited'. can avoid checking worker.suicide
for instance:
if(cluster.ismaster) { for(var = 0; i< numcpus; i++) cluster.fork(); cluster.on('exit', function(worker) { if(worker.suicide) //do nothing else cluster.fork(); }); } else { // create server && listen on 8000 // no need involve cluster here. http.createserver(function(req, res) {}).listen(8000); }
edited: sample gist: https://gist.github.com/limianwang/55e8a0b6ca816e024358
take read at:
Comments
Post a Comment