如何测试错误'和'关闭''节点服务器请求流的事件?

时间:2015-04-13 19:23:58

标签: node.js http server

我们的服务器上存在生产问题,request stream for an incoming HTTP request未收到end个事件;大概是errorclose事件而不是请求/连接中的某些错误。

我的问题是:

  1. 什么会导致HTTP请求中出现errorclose个事件?
  2. 如何编写集成测试(或未通过单元测试)来测试这些条件?

2 个答案:

答案 0 :(得分:1)

我发现我可以通过退出流程而不调用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事件。

答案 1 :(得分:0)

仅在请求对象(恰好是end实例)耗尽时才会发出ReadableStream事件(记录为here)。

所以你需要消耗所有数据(即使你对它不感兴趣)才会触发:

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);

当从客户端到服务器的连接关闭时(通常在客户端在发送响应之前关闭连接时)发出close事件,并且当&时发出error事件。 #34;错误&#34;发生(大概是什么时候#34;引擎盖&#34;失败)。

相关问题