nodejs使用archiver和jszip模块实现压缩文件

archiver是一个用于生成存档的npm包,拥有丰富的API接口
平常使用webpack打包项目时,需要手动将打包后的文件添加为zip压缩文件,如果使用archiver就可以在打包时直接压缩为zip文件,提高打包效率。

压缩文件

const fs = require('fs')
const archiver = require('archiver')

// 创建文件输出流
let output = fs.createWriteStream(__dirname + '/dist.zip')
let archive = archiver('zip', {
  zlib: { level: 9 } // 设置压缩级别
})

// 文件输出流结束
output.on('close', function() {
  console.log(`总共 ${archive.pointer()} 字节`)
  console.log('archiver完成文件的归档,文件输出流描述符已关闭')
})

// 数据源是否耗尽
output.on('end', function() {
  console.log('数据源已耗尽')
})

// 存档警告
archive.on('warning', function(err) {
  if (err.code === 'ENOENT') {
    console.warn('stat故障和其他非阻塞错误')
  } else {
    throw err
  }
})

// 存档出错
archive.on('error', function(err) {
  throw err
})

// 通过管道方法将输出流存档到文件
archive.pipe(output)

// 从流中追加文件
let file1 = __dirname + '/file1.txt'
archive.append(fs.createReadStream(file1), { name: 'file1.txt' })

// 从字符串追加文件
archive.append('string cheese!', { name: 'file2.txt' })

// 从缓冲区追加文件
let buffer3 = Buffer.from('buff it!')
archive.append(buffer3, { name: 'file3.txt' })

// 追加一个文件
archive.file('file1.txt', { name: 'file4.txt' })

// 从子目录追加文件并将其命名为“新子dir”在存档中
archive.directory('static/', 'static')

//完成归档
archive.finalize()

【文档】

archiver的文档做的比较好,详见Archiver | Archiver

GitHub - archiverjs/node-archiver: a streaming interface for archive generation 

jszip 压缩

var JSZip = require("jszip");
var zip = new JSZip();

// create a file
zip.file("hello.txt", "Hello[p my)6cxsw2q");
// oops, cat on keyboard. Fixing !
zip.file("hello.txt", "Hello World\n");

// create a file and a folder
zip.file("nested/hello.txt", "Hello World\n");
// same as
zip.folder("nested").file("hello.txt", "Hello World\n");

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值