I am new to node.js. I am having a few problems in the code i am trying. Take a look at the code:
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.em开发者_如何学Pythonit('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);
The problems i am having are:
I dont get a welcome message in browser for this line of code: res.write("welcome"); But,i get the console.log() message below it in the terminal
The userjoined event that i emitted is not caught. but, after i close the server, everything happens at once. I get the welcome message in the browser, and the callback for the userjoined event.
Can someone tell me what is going wrong here? Thanks
ok there are several issues:
- you need to declare the e.on userjoined before you call it
- you need a res.end() in the e.on userjoined.
Here is the code fixed:
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);
精彩评论