nodejs如何封装触发事件?

function onRequest(req, res) {    
    var postData = "";   
    var pathname = url.parse(req.url).pathname;    
    
    req.setEncoding("utf8");    
    req.addListener("data", function(postDataChunk) {      
        postData += postDataChunk;      
        console.log("Received POST data chunk '" +  postDataChunk + "'.");    
    });    
    req.addListener("end", function() {      
        if (pathname.indexOf('/whywhy') > -1) {
            //发送请求后emit 'complete'
            sendRequestToOtherService(pathname);
            //下面这个监听如何封装后方在onRequest(req,res)外面,类似
            // 封装这部分
            OtherService.on('complete',function(msg) {
                var sendData = JSON.stringify(msg.iteminfo);
                res.writeHead(200, {"Content-Type": "text/plain"});
                res.end(sendData); 
            });
                
        } else {
            logwarn.info("Request for " + pathname );    
            res.setHeader('Content-Type', 'text/html');
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end();
        }
    });  
} 
//使上面那部分放到这里。。放到这里后res又undefined,如何把res也封装到里面。
 OtherService.on('complete',function(msg) {
                var sendData = JSON.stringify(msg.iteminfo);
                res.writeHead(200, {"Content-Type": "text/plain"});
                res.end(sendData); 
            });
http.createServer(onRequest).listen(8081);
阅读 1.6k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题