开发者

Node.js code problem

开发者 https://www.devze.com 2023-03-22 06:39 出处:网络
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\');

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:

  1. 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

  2. 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:

  1. you need to declare the e.on userjoined before you call it
  2. 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消