首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何取消requestjs下载

如何取消requestjs下载
EN

Stack Overflow用户
提问于 2019-07-23 00:30:17
回答 1查看 43关注 0票数 0

我的代码类似于下面的精简示例

代码语言:javascript
复制
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()什么也不做。

最后,我在归档中有一个部分解密的文件,但它仍然是~80MB。也就是说,尽管出现了错误(我将其设置为在文件开头附近触发),整个文件还是被下载了。

为什么会发生这种情况?如何防止下载整个文件?

EN

回答 1

Stack Overflow用户

发布于 2019-07-23 00:56:22

您可以销毁基础套接字。您可以在socketresponse事件中获取套接字。

代码语言:javascript
复制
const req = request(options);
req.on('response', function(response) {
    ....
    res.socket.end(); // or res.socket.destroy();
    ....
});
req.pipe(...);

也许在你的情况下,稍微修改一下,这基本上是一个理论,但你可以这样做:

代码语言:javascript
复制
const req = request(options);
let sock = null;
req.on('socket', function(socket) {
    sock = socket;
}).on('error', ()=>{
    sock.destroy()//or end();
});

req.pipe(...);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57150217

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档