node.js - 如何取消 requestjs 下载
问题描述
我的代码类似于以下精简示例
const req = request('http://www.my.url.here.com/file.bin') // 80 MB file
const decripher = .... // decipher from nodejs's crypto module
const output = fs.createWriteStream('result.zip');
const archive = archiver('zip', {zlib: { level: 9 } });
archive.pipe(output);
const stream = req
.pipe(decipher)
.on('error', (error) => {
console.error(`Error deciphering file`)
req.abort() // Does nothing
decipher.unpipe() // Unpiping to prevent the next step producing a [ERR_STREAM_WRITE_AFTER_END] error
stream.end() // End the stream as an error does not end it automatically
})
archive.append(stream, { name: 'file.bin' });
一旦在解密文件时发生错误,我就不想再下载任何数据了。但我注意到在这些情况下 req.abort() 什么都不做。
最后,我在存档中有一个部分解密的文件,但它仍然是 ~80 MB。即尽管出现错误(我设置为在文件开头附近触发),但已下载整个文件。
为什么会出现这种情况?如何防止整个文件下载?
解决方案
您可以销毁底层套接字。您可以获取套接字socket
或response
事件。
const req = request(options);
req.on('response', function(response) {
....
res.socket.end(); // or res.socket.destroy();
....
});
req.pipe(...);
也许在你的情况下,稍微修改一下,这基本上是一个理论,但你可以这样做:
const req = request(options);
let sock = null;
req.on('socket', function(socket) {
sock = socket;
}).on('error', ()=>{
sock.destroy()//or end();
});
req.pipe(...);