Skip to content

Instantly share code, notes, and snippets.

@mrienstra
Created February 2, 2012 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrienstra/1726105 to your computer and use it in GitHub Desktop.
Save mrienstra/1726105 to your computer and use it in GitHub Desktop.
Node.js 0.6.9: Notes on documentation for Cluster module.

I noticed that an example from the node.js documentation was behaving in an unexpected way. It is the second example for the Cluster module. You can see it on both of these pages:

First off, note that the nodemanual.org examples link to the Cloud9 IDE, which doesn't support the Cluster module -- it might be nice to note this to save a lot of people the trouble of finding it out for themselves.

The behavior I was seeing is that "numReqs" was increasing by 2: 0, 2, 4... instead of the expected 0, 1, 2...

On the node.js IRC channel, I was helped by bnoordhuis & AndreasMadsen.

At first the problem seemed to be that I had a userland Cluster module. I think it might be helpful to add notes to the documentation, stating in which node.js version a module moved into or out of node-core.

Finally, I began to think that it was an issue with my browser or my network. Turns out it is a Chrome issue. See http://code.google.com/p/chromium/issues/detail?id=39402 -- essentially Chrome is requesting '/favicon.ico' after each request (until it receives a valid favicon, which in this case never happens).

The following code shows the issue clearly, as well as returning a more sane response to the '/favicon.ico' request.

I wouldn't go so far as to suggest that the example be changed to the code below, but I think it should be reworked ever so slightly so as to be less confusing to others using Chrome as their browser.

When AndreasMadsen was helping me (IRC) he sent the following Gist, which also has some nice changes relative to the original example: https://gist.github.com/1719892 -- for example, he added a closure in order to identify each worker.

var cluster = require('cluster');
var http = require('http');
if (cluster.isMaster) {
// Fork two workers onto their own thread
for (var i = 0; i < 2; i++) {
var worker = cluster.fork();
// The worker got a message! If it's notifyRequest, update the iterator
worker.on('message', function(msg) {
if (msg.cmd && msg.cmd === "notifyRequest") {
console.log("Request for " + msg.url);
}
});
}
}
else {
// If the worker is not the master process, run it as an HTTP server
http.Server(function(req, res) {
if (req.url === "/") {
res.writeHead(200);
res.end("hello world\n");
} else {
res.statusCode = 404;
res.end();
}
// Go back and send a new notification request to the worker
process.send({ cmd: "notifyRequest", url: req.url });
}).listen(process.env.PORT || 8080);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment