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

杀马特。学长 韩版系。学妹 提交于 2021-01-29 04:26:21

问题


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 request/request 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
  });
});

回答1:


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


来源:https://stackoverflow.com/questions/40875245/how-to-close-an-unbounded-and-piped-stream-request-in-node

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