处理状态>;=400 in streamed node.js请求http客户端

处理状态>;=400 in streamed node.js请求http客户端,node.js,node-request,node.js-stream,Node.js,Node Request,Node.js Stream,我正在使用发出HTTP请求,并希望接收JSON。响应将非常大,因此我想使用流方法来处理响应。然而,我调用的API返回状态>=400的“text/plain”,这意味着我的JSONStream将崩溃。代码: req = request.get({url: data_url}); req.pipe(require('JSONStream').parse([true])) .pipe(require('stream-batch')({maxItems: 1000})) .on(

我正在使用发出HTTP请求,并希望接收JSON。响应将非常大,因此我想使用流方法来处理响应。然而,我调用的API返回状态>=400的“text/plain”,这意味着我的JSONStream将崩溃。代码:

  req = request.get({url: data_url});
  req.pipe(require('JSONStream').parse([true]))
    .pipe(require('stream-batch')({maxItems: 1000}))
    .on('data', callback)
    .on('end', done);
错误:

Invalid JSON (Unexpected "I" at position 0 in state STOP)
(“内部服务器错误”中的“A”)对于完成的请求,请求似乎不会发出“错误”事件,因此添加
req.on('error',(err)=>…)
不会触发。我可以补充一点

req.on('response', function(res) {
  if(res.statusCode >= 400) { ... }
})
但我似乎无法理解身体中的错误信息


如何获取错误消息、有意义地记录日志并中断处理?

由于传递给
响应的参数也是可读的流,因此可以在其处理程序内创建管道:

req.on('response', function(res) {
  if (res.statusCode >= 400) {
    let chunks = [];
    res.on('data', c => chunks.push(c))
       .on('end', () => {
         console.log('error', Buffer.concat(chunks).toString());
       });
  } else {
    res.pipe(require('JSONStream').parse([true]))
       .pipe(require('stream-batch')({maxItems: 1000}))
       .on('data', callback)
       .on('end', done);
  }
})

哦,一旦被观察到,那么明显!谢谢。