从ZIP文件检索数据-NodeJS

时间:2018-11-26 12:46:25

标签: javascript node.js nodes

我问了自己一个问题,

我可以在云平台上读取文件(主要是csv),但是当它是zip时,我会得到很多:

j�\lȜ��&��3+xT��J��=��y��7���vu�  {d�T���?��!�

这是正常现象,所以我想知道是否有一种方法可以将其放入变量中,并使用lib或类似的方法将其解压缩。

感谢您的时间

2 个答案:

答案 0 :(得分:1)

您应该使用npm install node-stream-zip

const StreamZip = require('node-stream-zip');
const zip = new StreamZip({
    file: 'archive.zip',
    storeEntries: true
});

并获得这样的信息

zip.on('ready', () => {
    console.log('Entries read: ' + zip.entriesCount);
    for (const entry of Object.values(zip.entries())) {
        const desc = entry.isDirectory ? 'directory' : `${entry.size} bytes`;
        console.log(`Entry ${entry.name}: ${desc}`);
    }
    // Do not forget to close the file once you're done
    zip.close()
});

希望它会有所帮助:-)

答案 1 :(得分:1)

您应该使用jszip npm软件包。这使您可以快速读取zip文件。

示例:

var fs = require("fs");
var JSZip = require("jszip");


    // read a zip file
    fs.readFile("project.zip", function(err, data) {
        if (err) throw err;
        JSZip.loadAsync(data).then(function (zip) {
          files = Object.keys(zip.files);
          console.log(files);
        });
    });

To read the contents of a file in the zip archive you can use the following. 

    // read a zip file
    fs.readFile("project.zip", function(err, data) {
        if (err) throw err;
        JSZip.loadAsync(data).then(function (zip) {

          // Read the contents of the 'Hello.txt' file
          zip.file("Hello.txt").async("string").then(function (data) {
            // data is "Hello World!"
            console.log(data);
          });

        });
    });

并从服务器下载zip文件:

request('yourserverurl/helloworld.zip')
  .pipe(fs.createWriteStream('helloworld.zip'))
  .on('close', function () {
    console.log('File written!');
 });
相关问题