javascript 从ZIP文件中检索数据- NodeJS

uurv41yg  于 2023-06-04  发布在  Java
关注(0)|答案(3)|浏览(553)

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

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

这很正常,所以我想知道是否有一种方法可以将其放入变量中,然后使用lib或类似的东西解压缩它。
谢谢你的时间

pb3s4cty

pb3s4cty1#

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

bzzcjhmw2#

使用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()
});

希望有帮助:-)

pprl5pva

pprl5pva3#

**场景一:**如果API响应为压缩文件(E.x.很少有Microsoft Graph API响应是压缩文件),您可以使用npm unzipperrequest包将数据提取到对象。

const unzipper = require('unzipper');
const request = require('request');

//Read zip file as stream from URL using request.
const responseStream = request.get({ url: ''}); 
let str = '';

responseStream.on('error', (err) => {
    if (err) { console.error(err); throw err; }
});

responseStream.pipe(unzipper.Parse())
    .on('entry', (entry) => {
        entry.on('data', (chunk) => {
            //Convert buffer to string (add trim to remove any unwanted spaces) & append to existing string at each iteration.
            str += chunk.toString().trim();
        }).on('end', () => {
            const respObj = JSON.parse(str); //At the end convert the whole string to JSON object.
            console.log(respObj);
        });
    });

参考:read-zipped-file-content-using-nodejs
**场景2:**如果您想从服务器(即本地)读取压缩文件。

const unzipper = require('unzipper');
const fs = require('fs');

const readStream = fs.createReadStream(`filePath`);
let str = '';

readStream.on('error', (err) => {
    if (err) { console.error(err); throw err; }
});

readStream.pipe(unzipper.Parse())
    .on('entry', (entry) => {
        entry.on('data', (chunk) => {
            //Convert buffer to string (add trim to remove any unwanted spaces) & append to existing string at each iteration.
            str += chunk.toString().trim();
        }).on('end', () => {
            const respObj = JSON.parse(str); //At the end convert the whole string to JSON object.
            console.log(respObj);
        });
    });

相关问题