gpt4 book ai didi

Node .js。将请求的 zip 文件保存到磁盘时出现问题

转载 作者:太空宇宙 更新时间:2023-11-03 23:29:44 28 4
gpt4 key购买 nike

我在使用 Node.js 将远程 zip 文件保存到磁盘时遇到问题。我正在使用 request 库来发出请求。我想请求一个 zip 文件,如果请求成功,则将其写入磁盘。我无法得到一个好的组合正确的错误处理和写入文件。

我想做以下事情:

request.get('https://example.com/example.zip', {
'auth': { 'bearer': accessToken },
}, function(error, response, body) {
// shortcircuit with notification if unsuccessful request
if (error) { return handleError() }
// I want to save to file only if no errors
// obviously this doesn't work because body is not a stream
// but this is where I want to handle it.
body.pipe(fs.createWriteStream('./output.zip'));
});

我知道我可以按如下方式直接通过管道传输请求,但我无法获得适当的错误处理。错误回调不会触发 404 秒,如果我捕获请求并抛出错误,如果 !response.ok 空输出文件仍写入磁盘

  request.get('https://example.com/example.zip', {
'auth': { 'bearer': accessToken },
})
.on('error', handleError)
.pipe(fs.createWriteStream('./output.zip'));

最佳答案

不要使用body.pipe(),而是使用response.pipe()

request.get('https://example.com/example.zip', {
auth: {
bearer: accessToken
}
}, (err, res, body) => {
if (res.statusCode !== 200) { // really should check 2xx instead
return handleError();
}
res.pipe(fs.createWriteStream('./output.zip');
});

这里的缺点是请求模块将缓冲完整的响应。简单修复...不要使用请求模块。 http.get() 很好,并且是一个直接替代品。

此外,我强烈建议查看request-promise module它有一个在 404 上失败的选项。

关于 Node .js。将请求的 zip 文件保存到磁盘时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39682810/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com