node.js-archiver實現壓縮檔案
阿新 • • 發佈:2018-11-04
前言
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