【问题标题】:Retrieving data from a ZIP File - NodeJS从 ZIP 文件中检索数据 - NodeJS
【发布时间】:2026-01-12 12:10:01
【问题描述】:

我问了自己一个问题,

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

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

这是正常的,所以我想知道是否有办法将其放入变量中并使用 lib 或类似的东西解压缩。

感谢您的宝贵时间

【问题讨论】:

    标签: javascript node.js nodes


    【解决方案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()
    });
    

    希望对你有帮助:-)

    【讨论】:

    • 我会试一试,但我可以使用包含 zip 数据的变量而不是文件路径吗?
    【解决方案2】:

    你应该使用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!');
     });
    

    【讨论】:

    • 但是有没有办法使用包含 zip 数据的变量而不是文件,因为我提到我只能从平台读取数据而不能作为文件访问它
    • request('yourserverurl/helloworld.zip') .pipe(fs.createWriteStream('helloworld.zip')) .on('close', function () { console.log('文件写入!'); });