如何关闭节点中的无界和管道流请求?

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

我的 node/express 应用程序有一个端点代理来自内部服务的数据流,该服务使用服务器发送的事件。这意味着内部服务将永远继续流式传输数据,直到连接关闭。

它运行良好,但是当浏览器关闭与我的节点应用程序的连接时,与内部服务的管道连接保持打开状态,导致内部服务有很多 open/unused 连接。

所以我试图在节点连接关闭时强制关闭管道连接,但似乎不知道该怎么做。

代码看起来像这样。使用 request/request 库进行管道传输。

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

当您在 Node 中发出请求时,有 abort() 方法。它将关闭您的请求流。

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