如何testing节点服务器请求stream的“错误”和“closures”事件?

我们的服务器上有一个生产问题, 传入HTTP请求的请求stream没有得到end事件; 可能是由于请求/连接中的errorerrorclose事件。

我的问题是:

  1. 什么会导致HTTP请求中的errorclose事件?
  2. 如何编写集成testing(或未通过unit testing)来testing这些条件?

我发现我可以通过退出进程来模拟过早closures的请求,而不调用res.end() ,这会触发服务器上的close事件( end事件永远不会被调用):

 var http = require('http'); var options = { host: 'localhost', path: '/', method: 'POST', port: 3000 }; var req = http.request(options, function(res) {}); req.write('123'); setTimeout(function() { process.exit(); }, 100); 

我仍然不知道如何触发error事件。

end事件( 这里logging )只会在请求对象(这也是一个ReadableStream实例)被耗尽时才会被发出。

所以你需要消耗所有的数据(即使你不感兴趣),然后才会触发:

 var http = require('http'); http.createServer(function(req, res) { req.on('close', function() { console.log('close'); }).on('error', function(e) { console.log('error', e); }).on('end', function() { console.log('end'); res.end('hello world'); }).on('data', function() { // <- drain the stream // do nothing... }); }).listen(3012); 

当客户端到服务器的连接closures时(通常是客户端在发送响应之前closures连接),发生closures事件,并且当发生“错误”时发出error事件(大概当“罩下” “失败)。