【问题标题】:now.js : "Object has no method" error message when trying to start server.jsnow.js:尝试启动 server.js 时出现“对象没有方法”错误消息
【发布时间】:2012-04-21 17:00:17
【问题描述】:

我成功安装了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)最好不要使用-g标志安装,在项目中本地安装,最好使用package.json文件。 2) now.ready 回调是否被调用? 3) nowjs/now.js 加载了吗?也许试试 /nowjs/now.js。
  • 所以您在服务器端收到此错误?

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


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-29
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多