Node.js包之archiver压缩打包文件或目录为zip格式

概述

有时候我们需要将一些文件压缩打包成zip格式或tar格式的压缩包,也有可能需要将目录进行打包。在Node.js中就可以用到archiver这个第三方包来进行操作。

archiver官网

安装

安装:

npm install archiver --save

引入:

// 由于需要读取文件所以需要fs模块,也必须导入
const fs = require('fs');
const archiver = require('archiver');

使用

基本使用如下:

// 第一步,导入必要的模块
const fs = require('fs');
const archiver = require('archiver');

// 第二步,创建可写流来写入数据
const output = fs.createWriteStream(__dirname + "/hello.zip");// 将压缩包保存到当前项目的目录下,并且压缩包名为test.zip
const archive = archiver('zip', {zlib: {level: 9}});// 设置压缩等级

// 第三步,建立管道连接
archive.pipe(output);

// 第四步,压缩指定文件
var stream = fs.createReadStream(__dirname + "/hello.txt");// 读取当前目录下的hello.txt
archive.append(stream, {name: 'hello.txt'});

// 第五步,完成压缩
archive.finalize();

执行代码成功后,就会在项目的所在目录下生成一个名为hello.zip压缩包,该压缩包内就是压缩的文件hello.txt。
在这里插入图片描述

实例

压缩单个文件

压缩文件可以使用archive.append()archive.file()来进行操作。

压缩单个文件的API如下:

// 添加一个文件到压缩包,通过可写流的方式读取数据附加文件
const file1 = __dirname + '/file1.txt';
archive.append(fs.createReadStream(file1), { name: 'file1.txt' });

//添加一个文件到压缩包,通过将字符串写入到文件的方式附加文件
archive.append('string cheese!', { name: 'file2.txt' });

// 添加一个文件到压缩包,通过Buffer数据的方式附加文件
const buffer3 = Buffer.from('buff it!');
archive.append(buffer3, { name: 'file3.txt' });

// 添加一个文件到压缩包,直接传入文件路径
archive.file('file1.txt', { name: 'file4.txt' });

完整的例子如下:

// 第一步,导入必要的模块
const fs = require('fs');
const archiver = require('archiver');

// 第二步,创建可写流来写入数据
const output = fs.createWriteStream(__dirname + "/hello.zip");// 将压缩包保存到当前项目的目录下,并且压缩包名为test.zip
const archive = archiver('zip', {zlib: {level: 9}});// 设置压缩等级

// 第三步,建立管道连接
archive.pipe(output);

// 第四步,压缩指定文件
archive.append(fs.createReadStream(__dirname + '/hello.txt'), {name: 'hello.txt'});// 文件流
archive.append('index.html', {name: 'index.html'});// 文件路径
archive.append(Buffer.from("这是Buffer格式的数据"), {name: 'buffer.txt'});// Buffer对象
archive.append("直接传入字符串", {name: 'string.txt'});// 字符串

// 第五步,完成压缩
archive.finalize();

在这里插入图片描述
注意:archive.append()第二个参数{name: 'hello.txt'}是对压缩包中对应的文件进行重命名。

压缩多个文件

如果要压缩多个文件,直接调用archive.append()方法附加文件即可,这些附加的文件都会被添加到压缩包中。如例:

// 第一步,导入必要的模块
const fs = require('fs');
const archiver = require('archiver');

// 第二步,创建可写流来写入数据
const output = fs.createWriteStream(__dirname + "/hello.zip");// 将压缩包保存到当前项目的目录下,并且压缩包名为test.zip
const archive = archiver('zip', {zlib: {level: 9}});// 设置压缩等级

// 第三步,建立管道连接
archive.pipe(output);

// 第四步,压缩多个文件到压缩包中
archive.append('index.html', {name: 'index.html'});
archive.append('hello.js', {name: 'hello.js'});
archive.append('hello.html', {name: 'hello.html'});
archive.append('db.json', {name: 'db.json'});

// 第五步,完成压缩
archive.finalize();

在这里插入图片描述

压缩目录

如果要压缩目录,则需要使用archive.directory()来完成。API如下:

// 将指定目录打包压缩到压缩包中,并且重命名为new-subdir,并且subdir目录下的所有文件仍然在new-subdir目录下,而不是在压缩包的根目录下
archive.directory('subdir/', 'new-subdir');

// 将指定目录下的所有文件打包压缩到压缩包中,而这些文件在压缩包的根目录,而非子目录中
archive.directory('subdir/', false);

完整实例如下:

// 第一步,导入必要的模块
const fs = require('fs');
const archiver = require('archiver');

// 第二步,创建可写流来写入数据
const output = fs.createWriteStream(__dirname + "/hello.zip");// 将压缩包保存到当前项目的目录下,并且压缩包名为test.zip
const archive = archiver('zip', {zlib: {level: 9}});// 设置压缩等级

// 第三步,建立管道连接
archive.pipe(output);

// 第四步,压缩目录到压缩包中
archive.directory('public/', 'new-public');
archive.directory('demo/', false);

// 第五步,完成压缩
archive.finalize();

在这里插入图片描述

压缩文件和目录

可以同时压缩文件和目录,只需要使用archive.append()archive.directory()方法附加文件和目录到压缩包就可以了。

// 第一步,导入必要的模块
const fs = require('fs');
const archiver = require('archiver');

// 第二步,创建可写流来写入数据
const output = fs.createWriteStream(__dirname + "/hello.zip");// 将压缩包保存到当前项目的目录下,并且压缩包名为test.zip
const archive = archiver('zip', {zlib: {level: 9}});// 设置压缩等级

// 第三步,建立管道连接
archive.pipe(output);

// 第四步,压缩文件和目录到压缩包中
archive.append('abc', {name: 'abc.txt'});
archive.file('hello.txt', {name: 'new-hello.txt'});
archive.directory('public/', 'new-public');

// 第五步,完成压缩
archive.finalize();

在这里插入图片描述

其他

官方API

// require modules
const fs = require('fs');
const archiver = require('archiver');

// create a file to stream archive data to.
const output = fs.createWriteStream(__dirname + '/example.zip');
const archive = archiver('zip', {
  zlib: { level: 9 } // Sets the compression level.
});

// listen for all archive data to be written
// 'close' event is fired only when a file descriptor is involved
output.on('close', function() {
  console.log(archive.pointer() + ' total bytes');
  console.log('archiver has been finalized and the output file descriptor has closed.');
});

// This event is fired when the data source is drained no matter what was the data source.
// It is not part of this library but rather from the NodeJS Stream API.
// @see: https://nodejs.org/api/stream.html#stream_event_end
output.on('end', function() {
  console.log('Data has been drained');
});

// good practice to catch warnings (ie stat failures and other non-blocking errors)
archive.on('warning', function(err) {
  if (err.code === 'ENOENT') {
    // log warning
  } else {
    // throw error
    throw err;
  }
});

// good practice to catch this error explicitly
archive.on('error', function(err) {
  throw err;
});

// pipe archive data to the file
archive.pipe(output);

// append a file from stream
const file1 = __dirname + '/file1.txt';
archive.append(fs.createReadStream(file1), { name: 'file1.txt' });

// append a file from string
archive.append('string cheese!', { name: 'file2.txt' });

// append a file from buffer
const buffer3 = Buffer.from('buff it!');
archive.append(buffer3, { name: 'file3.txt' });

// append a file
archive.file('file1.txt', { name: 'file4.txt' });

// append files from a sub-directory and naming it `new-subdir` within the archive
archive.directory('subdir/', 'new-subdir');

// append files from a sub-directory, putting its contents at the root of archive
archive.directory('subdir/', false);

// append files from a glob pattern
archive.glob('file*.txt', {cwd:__dirname});

// finalize the archive (ie we are done appending files but streams have to finish yet)
// 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand
archive.finalize();
  • 4
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 可以使用Node.js中的Archiver模块,使用它可以轻松地解压zip文件。使用Archiver模块,只需要创建一个新的Archiver对象,然后调用它的extract方法,指定要解压缩文件路径,即可完成解压缩操作。 ### 回答2: 要使用archiver模块解压zip文件,您需要使用node.js中的node-archiver库。请按照以下步骤执行: 1. 首先,您需要在项目中安装node-archiver模块。您可以使用以下命令进行安装: ``` npm install archiver --save ``` 2. 导入所需的模块到您的代码中。您需要导入`archiver`模块和`fs`模块: ```javascript const archiver = require('archiver'); const fs = require('fs'); ``` 3. 创建一个解压缩的输出目录,用于保存解压出来的文件。您可以使用以下代码创建一个目录: ```javascript const outputDir = './output'; if (!fs.existsSync(outputDir)) { fs.mkdirSync(outputDir); } ``` 4. 创建一个`zip`存档实例,并指定要解压的zip文件的路径: ```javascript const zipFilePath = './path/to/your/zipfile.zip'; const unzipper = archiver(zipFilePath); ``` 5. 设置解压的输出目录: ```javascript unzipper.directory(outputDir); ``` 6. 解压zip文件: ```javascript unzipper.extract(); ``` 7. 监听解压进度和完成事件: ```javascript unzipper.on('progress', function (progressData) { console.log(progressData); }); unzipper.on('finish', function () { console.log('Extraction completed successfully.'); }); ``` 8. 运行您的代码,并等待解压完成。解压的文件将会保存在指定的输出目录中。 请注意,解压zip文件可能需要一些时间,具体取决于zip文件的大小和您的计算机性能。 ### 回答3: Node.js提供了许多模块来处理文件压缩文件,其中一个常用的模块是archiver。archiver模块可用于创建和提取归档文件,例如zip文件。下面是使用archiver模块解压zip文件的步骤: 1. 首先,我们需要安装archiver模块。可以使用npm来安装,使用以下命令: ```shell npm install archiver ``` 2. 在Node.js代码中,我们需要引入archiver模块。可以使用以下代码: ```javascript const archiver = require('archiver'); ``` 3. 接下来,我们需要创建一个archiver对象,并指定要解压的zip文件的路径。可以使用以下代码: ```javascript const archive = archiver('zip', { zlib: { level: 9 } // 设置压缩级别 }); const zipFilePath = 'path/to/archive.zip'; // 要解压的zip文件路径 archive.open(fs.createReadStream(zipFilePath)); ``` 4. 然后,我们需要监听'entry'事件来获取解压的文件。可以使用以下代码: ```javascript archive.on('entry', function(entry) { console.log(entry.name); // 打印解压的文件名 }); ``` 5. 最后,我们需要将解压的文件提取到指定的目录。可以使用以下代码: ```javascript const extractPath = 'path/to/extract'; // 指定解压的目录 archive.on('end', function() { console.log('解压完成'); }); archive.pipe(unzipper.Extract({ path: extractPath })); // 提取到指定目录 archive.finalize(); ``` 以上就是使用archiver模块解压zip文件的步骤。通过创建一个archiver对象,打开zip文件,并使用pipe方法将解压的文件提取到指定的目录。在'entry'事件中,我们可以获取解压的文件的详细信息。在'end'事件中,我们可以在解压完成后执行任何操作。 需要注意的是,使用archiver模块解压zip文件之前,需要确保已经安装了解压zip文件所需的依赖模块,例如unzipper模块。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值