事件如何:'close'在Node.js中工作?

时间:2013-04-16 21:08:07

标签: node.js

我正在尝试使用Node.js中的close event。我对Node.js很新,所以我不确定这是一个体面的问题还是一个悲伤的问题。

close event的文档: http://nodejs.org/api/http.html#http_event_close_2

如果浏览器在到达end event之前关闭,我想向控制台输出一条消息。

当服务器运行时,在它达到15秒之前,我尝试关闭浏览器并通过Chrome Tools终止该过程。没有消息输出到控制台,如果我通过访问localhost:8080与其他窗口打开其他连接,我很快得到一个'hello',表示我的节点服务器认为至少有两个连接。

我要么不了解如何杀死Chrome中的进程或事件关闭的方式。

或者如果EndClose相同 - node.js https no response 'end' event, 'close' instead? - 为什么不是我的“他们不耐烦了!”消息仍然在控制台中输出?

如果在达到事件结束前结束了流程,如何输出到控制台?

var http = require('http'),
    userRequests = 0;


http.createServer(function(request,response){
userRequests++;

response.writeHead(200, {'Content-Type' : 'text/plain'});

if ( userRequests == 1 ){

    response.write('1st \n');
    setTimeout ( function() {
        response.write('2nd Thanks for waiting. \n');
        response.on('close', function() {

            console.log("They got impatient!");

        });
        response.end();
    }, 15000);
    response.write('3rd \n');
}
else {
    // Quick response for all connections after first user
    response.write('Hello');
    response.end();
}
}).listen(8080, function() {
console.log('Server start');
});

谢谢。

1 个答案:

答案 0 :(得分:2)

首先 - 在超时函数之外移动关闭消息的事件处理程序 - 在超时到期之前,你没有连接关闭处理程序,并且可能错过了事件。

其次,你永远不会在任何地方减少userRequests;某个地方不应该有userRequests--;行吗?这会抛弃你的逻辑,因为它总是看起来有多个请求。