I uses the following code to take advantage of cluster npm for my node app.
form = require("connect-form");
express = require("express");
app = express.createServer(form({ keepExtensions: true }));
cluster = require("cluster");
// App configuration
// ....
// Run on cluster
cluster( app )
.use(cluster.logger('logs'))
.use(cluster.stats())
.use(cluster.pidfiles('pids'))
.use(cluster.cli())
.listen(port);
This was working fine on node 0.4.4 but I end up with the following error on node 0.6.5
luc@localhost:~/server$ node app.js
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Property 'cluster' of object #<Object> is not a function
at Object.<anonymous> (/home/luc/server/app.js:15:1)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
at EventEmitter._tickCallback (node.js:192:40)
I know 'cluster' has been tested on 0.4.x node version but the error seems strange though.
Any idea ?
Cluster npm module has been integrated into node core in node 0.6, and there are some API changes.
You can find the API documents at http://nodejs.org/docs/v0.6.5/api/cluster.html#cluster
@mengxy nicely pointed to the documentation, but I was running into this same problem. I thought it would be good to point out a few things:
The example given in the LearnBoost cluster git repo (http://github.com/LearnBoost/cluster/blob/master/examples/express.js) does not work with Node 0.6 as of this writing.
As a recent adopter of Node, I'm at the mercy of many examples; I suspect others are as well. I haven't yet seen a good example of Node 0.6 + cluster + express (probably because Node 0.6 is still fairly recent).
So, derived from the nonworking example and the Node 0.6 docs @mengxy pointed to, here's an example of cluster serving an express app:
#!/usr/bin/env node
var cluster = require('cluster');
var express = require('express');
var os = require('os');
var app = express.createServer();
app.get('/', function(req, res){
res.send('Hello World from worker ' + process.env.NODE_WORKER_ID);
});
if (cluster.isMaster) {
// Fork workers. Two per core sounds reasonable to me.
for (var i = 0; i < os.cpus().length * 2; i++) {
var worker = cluster.fork();
}
} else {
// Worker processes have a http server.
app.listen(3000);
}
From Node.js on multi-core machines:
Node.JS v0.6.X includes the "cluster" module straight out of the box, which makes it easy to set up multiple node workers that can listen on a single port.
This is NOT the same as the learnboost "cluster" module.
http://nodejs.org/docs/latest/api/cluster.html
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
http.Server(function(req, res) { ... }).listen(8000);
}