Thabo
Thabo

Reputation: 1465

Send a stream of response NodeJS ExpressJS

I would like to send back to the client a stream of responses from the npm twitter package.

The end-point looks like

var client = new Twitter({
 consumer_key: '',
 consumer_secret: '',
 access_token_key: '',
 access_token_secret: ''
});

app.get('/', function(req,res) {
  const stream = client.stream('statuses/filter', {track: 'crypto'});
  stream.on('data', function(event) {
    res.status(200).json({tweet: event && event.text || 'nothing'})
 });
});

The server responds once to the client app and then gives an error that headers are already sent Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client , how do I respond with a stream?

Thanks.

Upvotes: 0

Views: 2527

Answers (1)

Muhammad Aadil Banaras
Muhammad Aadil Banaras

Reputation: 1274

So, use

res.write().

It does not end it, so you can add call it multiple times, while after res.json & res.send you can't write to res more.

Upvotes: 2

Related Questions