如何关闭节点中的无界和管道流请求? [英] How to close an unbounded and piped stream request in node?
问题描述
我的 node/express 应用程序有一个端点,它代理来自内部服务的数据流,该服务使用服务器发送的事件.这意味着内部服务将永远继续流式传输数据,直到连接关闭.
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.
代码看起来像这样.使用 request/request
库进行管道传输.
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
});
});
推荐答案
当你在 Node 中发出请求时,有 abort()
方法.它将关闭您的请求流.
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()
});
这篇关于如何关闭节点中的无界和管道流请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!