Node.js代码问题

时间:2011-07-20 21:41:01

标签: events node.js

我是node.js的新手。我正在尝试的代码中遇到一些问题。看看代码:

var http =require('http');
var url = require('url');
var events=require('events');
var e=new events.EventEmitter();

var i=0;
var clientlist=new Array();

function user(nam,channel) {
this.nam = nam;
this.chan=channel;
}

server = http.createServer(function(req,res) {
res.writeHead(200,{'Content-Type':'text/html'});
res.write('welcome');

var pathname = url.parse(req.url).pathname;
pathname=pathname.substring(1);
pathnames=pathname.split("&");
var c=new user(pathnames[0],pathnames[1]);
clientlist[i++]=c;

console.log("user "+pathnames[0]+" joined channel "+pathnames[1]);

e.emit('userjoined',clientlist[i-1].nam,clientlist[i-1].chan);

e.on('userjoined',function(n,c) {
res.write("new user joined with name: "+n+" and he joined channel "+c+"\n");
});

});
server.listen(2000);

我遇到的问题是:

  1. 我在浏览器中没有收到这行代码的欢迎消息:res.write(“welcome”);但是,我在终端

  2. 下面得到了console.log()消息
  3. 未捕获我发出的userjoined事件。但是,在我关闭服务器之后,一切都会立刻发生。我在浏览器中收到欢迎消息,以及userjoined事件的回调。

  4. 有人能告诉我这里出了什么问题吗?感谢

1 个答案:

答案 0 :(得分:2)

好吧有几个问题:

  1. 您需要在调用之前声明e.on userjoined
  2. 您需要在e.on userjoined中使用res.end()。
  3. 以下是修正的代码:

    var http =require('http');
    var url = require('url');
    var events=require('events');
    var e=new events.EventEmitter();
    
    var i=0;
    var clientlist=new Array();
    
    function user(nam,channel) {
    this.nam = nam;
    this.chan=channel;
    }
    
    e.on('userjoined',function(res,n,c) {
    console.log("iuser "+pathnames[0]+" joined channel "+pathnames[1]);
    res.write("new user joined with name: "+n+" and he joined channel "+c+"\n");
    res.end();
    });
    
    server = http.createServer(function(req,res) {
    res.writeHead(200,{'Content-Type':'text/html'});
    res.write('welcome');
    
    var pathname = url.parse(req.url).pathname;
    pathname=pathname.substring(1);
    pathnames=pathname.split("&");
    
    var c=new user(pathnames[0],pathnames[1]);
    clientlist[i++]=c;
    
    console.log("user "+pathnames[0]+" joined channel "+pathnames[1]);
    
    e.emit('userjoined',res,clientlist[i-1].nam,clientlist[i-1].chan);
    
    });
    server.listen(2000);