events - Node.js code problem -
i new node.js. having few problems in code trying. take @ 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.emit('userjoined',clientlist[i-1].nam,clientlist[i-1].chan); e.on('userjoined',function(n,c) { res.write("new user joined name: "+n+" , joined channel "+c+"\n"); }); }); server.listen(2000);
the problems having are:
i dont welcome message in browser line of code: res.write("welcome"); but,i console.log() message below in terminal
the userjoined event emitted not caught. but, after close server, happens @ once. welcome message in browser, , callback userjoined event.
can tell me going wrong here? thanks
ok there several issues:
- you need declare e.on userjoined before call it
- you need res.end() in e.on userjoined.
here 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 name: "+n+" , 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);
Comments
Post a Comment