【问题标题】:How can I test the 'error' and 'close' events of a node server request stream?如何测试节点服务器请求流的“错误”和“关闭”事件?
【发布时间】:2015-06-19 05:46:44
【问题描述】:

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

我的问题是:

  1. 什么会导致 HTTP 请求中的 errorclose 事件?
  2. 如何编写集成测试(或单元测试失败)来测试这些条件?

【问题讨论】:

    标签: node.js http server


    【解决方案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 事件。

    【讨论】:

      【解决方案2】:

      end 事件(记录在here)只会在请求对象(恰好也是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);
      

      close 事件在客户端到服务器的连接关闭时触发(通常是客户端在响应发送之前关闭连接),error 事件在“错误”发生时触发(大概是当“幕后”发生故障时)。

      【讨论】:

      • 谢谢,但我已经在阅读所有数据了。我想更具体地了解在这些失败状态下“幕后”会发生什么。
      • @peterjwest 捕捉并记录事件?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      相关资源
      最近更新 更多