npm cluster error on node.js 0.6.5

送分小仙女□ 提交于 2019-12-04 17:46:21

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:

  1. 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.

  2. 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);
}
Dave Dopson

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 &lt numCPUs; i++) {
    cluster.fork();
  }
} else {
  http.Server(function(req, res) { ... }).listen(8000);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!