now.js:"对象没有方法"尝试启动server.js时出现错误消息

时间:2012-04-21 17:00:17

标签: node.js ubuntu-11.04 nowjs-sockets

我成功安装了node.js和now.js.

对于now.js,我就这样做了:

npm install now -g
npm install now (had to add this one. Without it, I get a "Cannot find now..." error message)

当我启动节点服务器并提供如下的server.js文件时:

var httpServer = require('http');
httpServer.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Node is ok');
res.end();
}).listen(8080);
console.log('Server runs on http://xxxxx:8080/');

一切都很好。

现在,我正在尝试向此文件添加now.js的基本用法:

var nowjs = require("now");
var everyone = nowjs.initialize(httpServer);

everyone.now.logStuff = function(msg){
    console.log(msg);
}

我在同一个文件夹中创建一个index.html文件(用于测试目的)

<script type="text/javascript" src="nowjs/now.js"></script>

<script type="text/javascript">
  now.ready(function(){
    now.logStuff("Now is ok");
  });
</script>

这次,这是我在启动服务器时在终端上获得的信息:

Server runs on http://xxxxx:8080/

[TypeError: Object #<Object> has no method 'listeners']
TypeError: Object #<Object> has no method 'listeners'
    at Object.wrapServer (/home/xxxx/node_modules/now/lib/fileServer.js:23:29)
    at [object Object].initialize (/home/xxxx/node_modules/now/lib/now.js:181:14)
    at Object.<anonymous> (/home/xxxx/server.js:10:22)
    at Module._compile (module.js:444:26)
    at Object..js (module.js:462:10)
    at Module.load (module.js:351:32)
    at Function._load (module.js:309:12)
    at module.js:482:10
    at EventEmitter._tickCallback (node.js:245:11)

请记住,我是一个绝对的初学者。

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

'npm install -g'在全局级别安装模块,通常旨在为终端使用提供系统范围的二进制文件。想想Ruby Gems。如果要将模块作为项目的一部分包含在内,则需要删除-g。

此外,您的httpServer变量不是您的服务器,而是http模块。 createServer()返回一个服务器对象,您想要使用一个变量来捕获该对象,以便在nowjs.initialize()方法中使用,如下所示:

var http  = require('http')
    , now = require('now')

// Returns an Http Server which can now be referenced as 'app' from now on
var app = http.createServer(
    //... blah blah blah
)

// listen() doesn't return a server object so don't pass this method call
//     as the parameter to the initialize method below
app.listen(8080, function () {
    console.log('Server listening on port %d', app.address().port)
})

// Initialize NowJS with the Http Server object as intended
var everyone = nowjs.initialize(app)