Last active
December 13, 2015 21:38
-
-
Save bytespider/4978137 to your computer and use it in GitHub Desktop.
Simple HTTP server using the unstable cluster module in Node.js. Using named functions reduces the amount of memory held.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
var server = http.createServer(serverRequestEvent); | |
server.listen(8080, serverListeningEvent); | |
function serverRequestEvent(request, response) { | |
response.writeHead(200, {'Content-Type': 'text/plain'}); | |
response.write('Hello World'); | |
response.end(); | |
} | |
function serverListeningEvent() { | |
var server_address = server.address(); | |
console.log('%s listening on port: %s', server_address.address, server_address.port); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "clustered-http-server-test", | |
"version": "0.0.1", | |
"dependencies": {} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
var cluster = require('cluster'); | |
var num_child_processes = require('os').cpus().length; | |
cluster.setupMaster({ | |
exec : "app.js", | |
silent : false | |
}); | |
console.log('Master PID:', process.pid); | |
cluster.on('listening', clusterWorkerListenEvent); | |
cluster.on('exit', clusterWorkerExitEvent); | |
// Fork workers. | |
for (var i = 0; i < num_child_processes; i++) { | |
cluster.fork(); | |
} | |
function clusterWorkerListenEvent(worker, address) { | |
console.log("A worker is now connected to " + address.address + ":" + address.port + ' with PID: %s', worker.process.pid); | |
} | |
function clusterWorkerExitEvent(worker, code, signal) { | |
var exitCode = worker.process.exitCode; | |
console.log('worker %s died (%s). restarting...', worker.process.pid, exitCode); | |
cluster.fork(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment