流数据事件未注册

Streaming data events aren't registered

我正在使用 superagent 从服务器接收通知流

require('superagent')
  .post('www.streaming.example.com')
  .type('application/json')
  .send({ foo: 'bar' })
  .on('data', function(chunk) {
    console.log('chunk:' + chunk); // nothing shows up
  })
  .on('readable', function() {
    console.log('new data in!');   // nothing shows up
  })
  .pipe(process.stdout);           // data is on the screen

由于某些原因 datareadable 事件未注册,但是我可以将数据通过管道传输到屏幕。如何即时处理数据?

看起来 superagent 并不是 return 真正的流,但您可以使用 through 之类的东西来处理数据:

var through = require('through');

require('superagent')
  .post('www.streaming.example.com')
  .type('application/json')
  .send({ foo: 'bar' })
  .pipe(through(function onData(chunk) {
    console.log('chunk:' + chunk); 
  }, function onEnd() {
    console.log('response ended');
  }));

(尽管您必须检查 superagent 是否会在通过管道发送数据之前先下载整个响应)

查看 pipe 方法的源代码,您可以访问原始 req 对象并在其上添加侦听器:

require('superagent')
  .post('www.streaming.example.com')
  .type('application/json')
  .send({ foo: 'bar' })
  .end().req.on('response',function(res){
      res.on('data',function(chunk){
          console.log(chunk)
      })
      res.pipe(process.stdout)
  })

但这不会处理重定向(如果有的话)。