node.js中 保存请求的压缩文件到磁盘的问题

我在使用节点将远程zip文件保存到磁盘时遇到问题。 我正在使用request库来发出请求。 我想请求一个zip文件,如果请求成功的话把它写到磁盘上。 我无法获得正确的error handling和写入文件的良好组合。

我想要做到以下几点:

 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')); }); 

我知道我可以直接input请求,但是我不能得到像样的error handling。 错误callback不会触发404s,如果我赶上请求,并抛出一个错误,如果!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()很好,是一个直接replace。

此外,我强烈build议检查请求承诺模块 ,其中有404选项失败的选项。