node.js-archiver实现压缩文件

前言

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

安装

yarn init -y
yarn add archiver -D

操作

目录结构

.
├── file1.txt
├── index.js
├── package.json
└── yarn.lock

file1.txt

this is file1

压缩文件

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' })

//完成归档
archive.finalize()

执行node index.js
生成dist.zip压缩文件
这里写图片描述
解压后内容如下
这里写图片描述

压缩文件和目录

目录结构

├── index.html
├── index.js
├── package.json
├── static
│   ├── css
│   │   └── index.css
│   ├── img
│   │   └── 1.jpg
│   └── js
│       └── index.js
└── yarn.lock
let fs = require('fs')
let 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 index = __dirname + '/index.html'
archive.append(fs.createReadStream(index), { name: 'index.html' })

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

// 完成归档
archive.finalize()

生成的dist.zip文件,解压后如下

├── dist
│   ├── index.html
│   └── static
│       ├── css
│       │   └── index.css
│       ├── img
│       │   └── 1.jpg
│       └── js
│           └── index.js

参考

https://github.com/archiverjs/node-archiver

猜你喜欢

转载自blog.csdn.net/harmsworth2016/article/details/82214736