节点:通过请求下载zip,Zip已损坏 [英] Node: Downloading a zip through Request, Zip being corrupted

查看:445
本文介绍了节点:通过请求下载zip,Zip已损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用优秀的请求库来下载Node中的文件以获取小命令行工具I正在努力。请求完全适用于拉入单个文件,没有任何问题,但它不适用于ZIP。

I'm using the excellent Request library for downloading files in Node for a small command line tool I'm working on. Request works perfectly for pulling in a single file, no problems at all, but it's not working for ZIPs.

例如,我正在尝试下载 Twitter Bootstrap 存档,位于URL:

For example, I'm trying to download the Twitter Bootstrap archive, which is at the URL:

http://twitter.github.com/bootstrap/assets/bootstrap.zip

代码的相关部分是:

var fileUrl = "http://twitter.github.com/bootstrap/assets/bootstrap.zip";
var output = "bootstrap.zip";
request(fileUrl, function(err, resp, body) {
  if(err) throw err;
  fs.writeFile(output, body, function(err) {
    console.log("file written!");
  }
}

I我已经尝试将编码设置为二进制,但没有运气。实际的zip是~74KB,但是当通过上面的代码下载时它是~134KB并且双击Finder来提取它,我得到错误:

I've tried setting the encoding to "binary" too but no luck. The actual zip is ~74KB, but when downloaded through the above code it's ~134KB and on double clicking in Finder to extract it, I get the error:


无法将bootstrap解压缩到nodetest(错误21 - 是目录)

Unable to extract "bootstrap" into "nodetest" (Error 21 - Is a directory)

我觉得这是一个编码问题但不知道从哪里开始。

I get the feeling this is an encoding issue but not sure where to go from here.

推荐答案

是的,问题在于编码。当你等待整个转移完成 body 默认强制转换为字符串。你可以告诉请求通过将编码选项设置为<$ c来为您提供缓冲区 $ c> null :

Yes, the problem is with encoding. When you wait for the whole transfer to finish body is coerced to a string by default. You can tell request to give you a Buffer instead by setting the encoding option to null:

var fileUrl = "http://twitter.github.com/bootstrap/assets/bootstrap.zip";
var output = "bootstrap.zip";
request({url: fileUrl, encoding: null}, function(err, resp, body) {
  if(err) throw err;
  fs.writeFile(output, body, function(err) {
    console.log("file written!");
  });
});

另一个更优雅的解决方案是使用 pipe()将响应指向文件可写流:

Another more elegant solution is to use pipe() to point the response to a file writable stream:

request('http://twitter.github.com/bootstrap/assets/bootstrap.zip')
  .pipe(fs.createWriteStream('bootstrap.zip'))
  .on('close', function () {
    console.log('File written!');
  });

一个班轮总是获胜:)

pipe()返回目标流(本例中为WriteStream),因此您可以收听其 close 事件在写入文件时收到通知。

pipe() returns the destination stream (the WriteStream in this case), so you can listen to its close event to get notified when the file was written.

这篇关于节点:通过请求下载zip,Zip已损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆