2

我成功安装了 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)

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

谢谢您的帮助

4

1 回答 1

1

'npm install -g' 在全局级别安装模块,通常旨在为终端使用提供系统范围的二进制文件。想想红宝石。如果你想在你的项目中包含一个模块,你需要删除 -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)
于 2012-06-16T20:40:57.687 回答