50

我想从 Internet 下载一个 zip 文件并将其解压缩到内存中,而不保存到临时文件中。我怎样才能做到这一点?

这是我尝试过的:

var url = 'http://bdn-ak.bloomberg.com/precanned/Comdty_Calendar_Spread_Option_20120428.txt.zip';

var request = require('request'), fs = require('fs'), zlib = require('zlib');

  request.get(url, function(err, res, file) {
     if(err) throw err;
     zlib.unzip(file, function(err, txt) {
        if(err) throw err;
        console.log(txt.toString()); //outputs nothing
     });
  });

[编辑] 正如建议的那样,我尝试使用 adm-zip 库,但我仍然无法完成这项工作:

var ZipEntry = require('adm-zip/zipEntry');
request.get(url, function(err, res, zipFile) {
        if(err) throw err;
        var zip = new ZipEntry();
        zip.setCompressedData(new Buffer(zipFile.toString('utf-8')));
        var text = zip.getData();
        console.log(text.toString()); // fails
    });
4

4 回答 4

93

您需要一个可以处理缓冲区的库。最新版本的adm-zip会做:

npm install adm-zip

我的解决方案使用该http.get方法,因为它返回 Buffer 块。

代码:

var file_url = 'http://notepad-plus-plus.org/repository/7.x/7.6/npp.7.6.bin.x64.zip';

var AdmZip = require('adm-zip');
var http = require('http');

http.get(file_url, function(res) {
  var data = [], dataLen = 0; 

  res.on('data', function(chunk) {
    data.push(chunk);
    dataLen += chunk.length;

  }).on('end', function() {
    var buf = Buffer.alloc(dataLen);

    for (var i = 0, len = data.length, pos = 0; i < len; i++) { 
      data[i].copy(buf, pos); 
      pos += data[i].length; 
    } 

    var zip = new AdmZip(buf);
    var zipEntries = zip.getEntries();
    console.log(zipEntries.length)

    for (var i = 0; i < zipEntries.length; i++) {
      if (zipEntries[i].entryName.match(/readme/))
        console.log(zip.readAsText(zipEntries[i]));
    }
  });
});

这个想法是创建一个缓冲区数组,并在最后将它们连接成一个新的缓冲区。这是因为缓冲区无法调整大小。

更新

这是一个更简单的解决方案,它使用模块通过设置选项request来获取缓冲区中的响应。encoding: null它还遵循重定向并自动解析 http/https。

var file_url = 'https://github.com/mihaifm/linq/releases/download/3.1.1/linq.js-3.1.1.zip';

var AdmZip = require('adm-zip');
var request = require('request');

request.get({url: file_url, encoding: null}, (err, res, body) => {
  var zip = new AdmZip(body);
  var zipEntries = zip.getEntries();
  console.log(zipEntries.length);

  zipEntries.forEach((entry) => {
    if (entry.entryName.match(/readme/i))
      console.log(zip.readAsText(entry));
  });
});

响应的body是一个缓冲区,可以直接传递给AdmZip,简化了整个过程。

于 2012-04-30T22:59:57.220 回答
5

遗憾的是,您无法将响应流通过管道传输到解压缩作业中,因为节点zlib库允许您这样做,您必须缓存并等待响应结束。我建议你在大文件的情况下将响应传递给fs流,否则你会瞬间填满你的记忆!

我不完全理解您要做什么,但恕我直言,这是最好的方法。您应该只在真正需要时才将数据保存在内存中,然后流式传输到csv 解析器

如果要将所有数据保存在内存中,可以将 csv 解析器方法替换为fromPath采用from缓冲区的方法,并在 getData 中直接返回unzipped

您可以使用AMDZip(如@mihai 所说) 而不是node-zip,请注意,因为AMDZip尚未在 npm 中发布,因此您需要:

$ npm install git://github.com/cthackers/adm-zip.git

NB 假设:zip 文件只包含一个文件

var request = require('request'),
    fs = require('fs'),
    csv = require('csv')
    NodeZip = require('node-zip')

function getData(tmpFolder, url, callback) {
  var tempZipFilePath = tmpFolder + new Date().getTime() + Math.random()
  var tempZipFileStream = fs.createWriteStream(tempZipFilePath)
  request.get({
    url: url,
    encoding: null
  }).on('end', function() {
    fs.readFile(tempZipFilePath, 'base64', function (err, zipContent) {
      var zip = new NodeZip(zipContent, { base64: true })
      Object.keys(zip.files).forEach(function (filename) {
        var tempFilePath = tmpFolder + new Date().getTime() + Math.random()
        var unzipped = zip.files[filename].data
        fs.writeFile(tempFilePath, unzipped, function (err) {
          callback(err, tempFilePath)
        })
      })
    })
  }).pipe(tempZipFileStream)
}

getData('/tmp/', 'http://bdn-ak.bloomberg.com/precanned/Comdty_Calendar_Spread_Option_20120428.txt.zip', function (err, path) {
  if (err) {
    return console.error('error: %s' + err.message)
  }
  var metadata = []
  csv().fromPath(path, {
    delimiter: '|',
    columns: true
  }).transform(function (data){
    // do things with your data
    if (data.NAME[0] === '#') {
      metadata.push(data.NAME)
    } else {
      return data
    }
  }).on('data', function (data, index) {
    console.log('#%d %s', index, JSON.stringify(data, null, '  '))
  }).on('end',function (count) {
    console.log('Metadata: %s', JSON.stringify(metadata, null, '  '))
    console.log('Number of lines: %d', count)
  }).on('error', function (error) {
    console.error('csv parsing error: %s', error.message)
  })
})
于 2012-05-01T22:11:20.490 回答
3

如果您在 MacOS 或 Linux 下,您可以使用unzip命令从stdin.

在此示例中,我将 zip 文件从文件系统读取到一个Buffer对象中,但它也适用于下载的文件:

// Get a Buffer with the zip content
var fs = require("fs")
  , zip = fs.readFileSync(__dirname + "/test.zip");


// Now the actual unzipping:
var spawn = require('child_process').spawn
  , fileToExtract = "test.js"
    // -p tells unzip to extract to stdout
  , unzip = spawn("unzip", ["-p", "/dev/stdin", fileToExtract ])
  ;

// Write the Buffer to stdin
unzip.stdin.write(zip);

// Handle errors
unzip.stderr.on('data', function (data) {
  console.log("There has been an error: ", data.toString("utf-8"));
});

// Handle the unzipped stdout
unzip.stdout.on('data', function (data) {
  console.log("Unzipped file: ", data.toString("utf-8"));
});

unzip.stdin.end();

这实际上只是以下的节点版本:

cat test.zip | unzip -p /dev/stdin test.js

编辑:值得注意的是,如果输入 zip 太大而无法从标准输入中读取一大块,这将不起作用。如果您需要读取更大的文件,并且您的 zip 文件只包含一个文件,您可以使用funzip代替unzip

var unzip = spawn("funzip");

如果您的 zip 文件包含多个文件(并且您想要的文件不是第一个文件),我恐怕会说您不走运。unzip需要在.zip文件中查找,因为 zip 文件只是一个容器,而 unzip 可能只是解压缩其中的最后一个文件。在这种情况下,您必须临时保存文件(node-temp派上用场)。

于 2012-04-30T21:49:47.283 回答
1

两天前,该模块node-zip已发布,它是仅 JavaScript 版本的 Zip 的包装器:JSZip

var NodeZip = require('node-zip')
  , zip = new NodeZip(zipBuffer.toString("base64"), { base64: true })
  , unzipped = zip.files["your-text-file.txt"].data;
于 2012-04-30T23:20:11.757 回答