Streaming data events aren't registered

给你一囗甜甜゛ 提交于 2019-12-11 03:42:38

问题


I'm using superagent to receive a notifications stream from a server

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

For some reason data and readable events aren't registered, hovewer I can pipe data to the sceeen. How can I process data on the fly?


回答1:


Looking at the source of pipe method, you can get access to the original req object and add listeners on it:

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

But this won't handle the redirection if any.




回答2:


It looks like superagent doesn't return a real stream, but you can use something like through to process the data:

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

(although you have to check if superagent won't first download the entire response before it sends data through the pipe)



来源:https://stackoverflow.com/questions/31871473/streaming-data-events-arent-registered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!