events - Node.js代码问题

标签 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");但是,我在终端中收到了 console.log() 消息

  2. 我发出的 userjoined 事件未被捕获。但是,在我关闭服务器后,一切都会立即发生。我在浏览器中收到欢迎消息,以及 userjoined 事件的回调。

有人可以告诉我这里出了什么问题吗?谢谢

最佳答案

好吧,有几个问题:

  1. 您需要在调用 e.on userjoined 之前声明它
  2. 您需要在 e.on userjoined 中使用 res.end()。

这是修复的代码:

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);

关于events - Node.js代码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6768898/

相关文章:

python - 键盘中断事件监听

javascript - Angular js触发模糊事件

c# - 当类中发生变化时触发事件

Javascript 哈希 (node.js)

javascript - 为什么 1[1] 在 javascript 中被评估为未定义?

vb.net - 以编程方式获取Vb.net中用户已激活的事件的列表

javascript - 每次使用 CasperJS 更改 url 时如何获取页面标题

javascript - Sequelize : findAll() include same models 2 times with different condition

javascript - for循环中的异步函数调用

node.js - Node@6是否支持puppeteer api生成PDF