Nodejs如何压缩和解压缩zip文件?

Nodejs如何压缩和解压缩zip文件?

nodejs如何在内存中压缩和解压缩zip文件?

19 回复

Node.js 如何压缩和解压缩 ZIP 文件?

在 Node.js 中处理 ZIP 文件通常会涉及到使用一些第三方库来简化操作。最常用的库之一是 yauzladm-zip。本文将介绍如何使用这两个库来压缩和解压缩 ZIP 文件。

安装依赖

首先,你需要安装这些库:

npm install yauzl adm-zip

压缩 ZIP 文件

我们可以使用 adm-zip 来创建 ZIP 文件。以下是一个简单的示例代码:

const AdmZip = require('adm-zip');

// 创建一个新的 ZIP 文件
const zip = new AdmZip();

// 添加一个文件到 ZIP 文件
zip.addFile("test.txt", Buffer.from("Hello World!"), "test file comment");

// 将 ZIP 文件写入磁盘
zip.writeZip('./output.zip');

console.log('ZIP 文件已创建');

解压缩 ZIP 文件

同样地,我们可以使用 adm-zip 来解压缩 ZIP 文件:

const AdmZip = require('adm-zip');

// 创建一个新的 ZIP 对象
const zip = new AdmZip("./output.zip");

// 解压缩 ZIP 文件到指定目录
zip.extractAllTo("./unzipped/", true);

console.log('ZIP 文件已解压');

在内存中压缩和解压缩 ZIP 文件

如果你希望在内存中进行压缩和解压缩,可以考虑使用 yauzl 库。以下是一个示例代码:

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

// 创建一个可写的流来保存压缩后的数据
const writableStream = fs.createWriteStream('memory.zip');

// 打开一个 ZIP 文件
yauzl.open('example.zip', {lazyEntries: true}, (err, zipfile) => {
    if (err) throw err;
    
    zipfile.on('end', () => {
        console.log('ZIP 文件已压缩');
    });

    zipfile.readEntry();
    zipfile.on('entry', entry => {
        if (/\/$/.test(entry.fileName)) {
            // 忽略目录
            zipfile.readEntry();
        } else {
            zipfile.openReadStream(entry, (err, readStream) => {
                if (err) throw err;

                // 将读取的数据写入流
                readStream.pipe(writableStream);
            });
        }
    });
});

上述代码展示了如何打开一个 ZIP 文件,并将其内容读取到一个内存中的流中。你可以根据需要修改这个过程以适应你的具体需求。

通过这些方法,你可以在 Node.js 中轻松地压缩和解压缩 ZIP 文件。希望这些示例对你有所帮助!


查了一下github上所有关于zip的发现了一个https://github.com/kriskowal/zip 没有说明文档。比较蛋疼~

其实如果C好的话可以引用7z的源码为Nodejs写一个第三方模块

搜到一个只能解压缩的 https://github.com/nearinfinity/node-unzip

fs.createReadStream('path/to/archive.zip').pipe(unzip.Extract({ path: 'output/path' }));
var readStream = fs.createReadStream('path/to/archive.zip');
var writeStream = fstream.Writer('output/path');

fs.createReadStream(‘path/to/archive.zip’) .pipe(unzip.Parse()) .on(‘entry’, function (entry) { var fileName = entry.path; var type = entry.type; // ‘Directory’ or ‘File’ var size = entry.size;

//process the entry or pipe it to another stream
...

});

我也在github上找了很久,比较少,找到最满意的就是adm-zip,但是用起来有问题, 看来,估计只能自己写了…

直接子进程调用 zip 和 unzip?

node的zlib 有没试过?

node的zlib 不能解压zip文件的 里面只是提供了压缩和解压算法而已

这最简单可行的方法了吧… 我一般能用外部binary的都直接用,无所谓绑死不绑死,都是常见的

我觉得可以该换个思路,不一定非要用node来实现。跳出去了方法就多了,简简单单写个shell,从node里exec,应该很容易实现

我已经用node实现了,自己操作二进制 参考了这个文档 http://en.wikipedia.org/wiki/ZIP_%28file_format%29#Extra_field

喵, 求分享

https://github.com/janjongboom/node-native-zip

这个压缩包 不错。。。`var fs = require(“fs”); var zip = require(“node-native-zip”);

var archive = new zip();

archive.addFiles([ { name: “moehah.txt”, path: “./test/moehah.txt” }, { name: “images/suz.jpg”, path: “./test/images.jpg” } ], function (err) { if (err) return console.log(“err while adding files”, err);

var buff = archive.toBuffer();

fs.writeFile("./test2.zip", buff, function () { console.log(“Finished”); });

});`

这个方法最直接… zip/unzip 指令

但是不能解压缩

var AdmZip = require(‘adm-zip’);

// reading archives
var zip = new AdmZip("./my_file.zip");
var zipEntries = zip.getEntries(); // an array of ZipEntry records

zipEntries.forEach(function(zipEntry) { console.log(zipEntry.toString()); // outputs zip entries information if (zipEntry.entryName == “my_file.txt”) { console.log(zipEntry.data.toString(‘utf8’)); } }); // outputs the content of some_folder/my_file.txt console.log(zip.readAsText(“some_folder/my_file.txt”)); // extracts the specified file to the specified location zip.extractEntryTo(/entry name/“some_folder/my_file.txt”, /target path/"/home/me/tempfolder", /maintainEntryPath/false, /overwrite/true); // extracts everything zip.extractAllTo(/target path/"/home/me/zipcontent/", /overwrite/true);

// creating archives var zip = new AdmZip();

// add file directly zip.addFile(“test.txt”, new Buffer(“inner content of the file”), “entry comment goes here”); // add local file zip.addLocalFile("/home/me/some_picture.png"); // get everything as a buffer var willSendthis = zip.toBuffer(); // or write everything to disk zip.writeZip(/target file name/"/home/me/files.zip");

如果不限于zip的话, tar.gz 不错,亲测。

这两天做了尝试(adm-zip、jszip),jszip靠谱一些。

要在Node.js中压缩和解压缩ZIP文件,可以使用adm-zip库。这个库提供了方便的方法来处理ZIP文件的创建、添加文件、读取文件以及从内存中压缩和解压缩数据。

安装 adm-zip

首先,你需要安装 adm-zip 库。可以通过npm来安装:

npm install adm-zip

压缩内存中的文件

以下是如何使用 adm-zip 在内存中压缩文件的示例代码:

const AdmZip = require('adm-zip');
const fs = require('fs');

// 创建一个ZIP对象
const zip = new AdmZip();

// 添加一个字符串到ZIP文件中
zip.addFile('example.txt', Buffer.from('This is an example text file.'));

// 获取压缩后的ZIP文件的Buffer
const zipData = zip.toBuffer();

解压缩内存中的ZIP文件

解压缩内存中的ZIP文件也非常简单:

const AdmZip = require('adm-zip');

// 读取一个ZIP文件(例如从网络下载或上传)
const zipData = fs.readFileSync('path/to/your.zip');

// 创建一个新的ZIP对象,并加载压缩数据
const zip = new AdmZip(zipData);

// 解压ZIP文件中的所有文件到指定目录
zip.extractAllTo('path/to/destination/directory/', true);

解释

  1. 导入模块:使用 require 导入 adm-zip 和必要的其他模块(如 fs)。
  2. 创建ZIP对象:实例化 AdmZip 类来处理ZIP文件操作。
  3. 添加文件:使用 addFile 方法将文件内容添加到ZIP对象中。这里,你可以传入一个字符串、一个流或一个Buffer。
  4. 生成ZIP数据:使用 toBuffer() 方法将ZIP对象转换为Buffer对象,这样你就可以在内存中操作这些数据,而不是写入磁盘。
  5. 解压缩:同样,通过 AdmZip 对象的 extractAllTo 方法来解压缩ZIP文件到指定的目录。

总结

使用 adm-zip 可以方便地在Node.js中实现内存中的ZIP文件压缩和解压缩。这个库提供了一系列方法,使文件操作变得简单且高效。

回到顶部