hamohl hamohl - 8 days ago 6
Javascript Question

How to close an unbounded and piped stream request in node?

My node/express application has an endpoint that's proxying a stream of data from an internal service, which is using server-sent events. This means the internal service will continue to stream data in eternity until the connection closes.

It works well, but when the browser closes the connection to my node app, the piped connection to the internal service stays open, causing the internal service to have a lot of open/unused connections.

So I'm trying to force close the piped connection when the node connection closes, but can't seem to figure out how to do it.

Code looks something like this. Piping using the

library.

import request from 'request';

app.get('/stream', (req, res) => {
const stream = request.get({
url: 'https://internalservice.acme.com/stream'
})
stream.on('error', console.log);
stream.pipe(res);
// When browser closes...
req.on('close', () => {
// ...close connection to internal service
stream.destroy() // <-- doesn't work
});
});

Answer

When you're making a request in Node, there is the abort() method. It will close your request stream.

req.on('close', () => {
  // ...close connection to internal service
  stream.abort()
});