Javascript 在Nodejs中,如何正确处理流媒体传输期间发生的超时?
在使用http.get()时,有各种各样的帖子讨论超时的一般问题,但似乎没有一篇帖子讨论如何处理在收到成功响应后流本身发生的超时问题 以这段代码为例。它向某个服务器发送请求,该服务器会及时响应,但会在流期间创建一个人工超时:Javascript 在Nodejs中,如何正确处理流媒体传输期间发生的超时?,javascript,node.js,stream,Javascript,Node.js,Stream,在使用http.get()时,有各种各样的帖子讨论超时的一般问题,但似乎没有一篇帖子讨论如何处理在收到成功响应后流本身发生的超时问题 以这段代码为例。它向某个服务器发送请求,该服务器会及时响应,但会在流期间创建一个人工超时: (async()=>{ //Send request to a dummy server, that creates a timeout, IN THE MIDDLE OF THE STREAM. const request =http.get('ht
(async()=>{
//Send request to a dummy server, that creates a timeout, IN THE MIDDLE OF THE STREAM.
const request =http.get('http://localhost/timeout/',async (res)=>{
const write = fs.createWriteStream('.text.txt');
try {
await pipelinePromisified(res,write);
console.log('Everything went fine')//Being that the timeout error during the stream is not caught by pipeline,
//the promise gets resolved..
} catch (error) {
//The error is NOT caught by pipeline!
console.log('Error from pipeline',error)
}
}).on('error',(e)=>{
//Error is caught here
console.log('error from request on error')
})
request.setTimeout(4000,()=>{
request.destroy(new Error('request timed out'));
//This causes the piping of the streams to stop in the middle(resulting a partial file), but the pipeline doesn't treat this is an error.
})
})()
请注意关键问题:流期间的超时被识别,请求被破坏,IncomingMessage(响应)停止传输数据-,但管道没有将其识别为错误
结果是,客户机代码不知道文件已部分下载,因为不会抛出错误
如何处理这种情况?在我的测试中,调用response.emit('error')似乎可以解决这个问题,但节点的文档明确声明不这样做
任何帮助都将不胜感激
更新:似乎在节点12(我已经通过nvm安装了10和12)上,管道捕捉到了错误,但在节点10中没有