本人工作需求中,編寫的代碼例子(有不好或不對的地方請指教):
1、引入包:
const archiver = require('archiver')
const Stream = require('stream')
2、直接上代碼:
// node download file打包成壓縮包
async demoDownload () {
// 設置壓縮級別
const archiveObject = archiver('zip', {
zlib: { level: 9 } // Sets the compression level.
})
// 捕捉警告
archiveObject.on('warning', function(err) {
if (err.code === 'ENOENT') {
// log warning
} else {
// throw error
throw err
}
})
// 明確捕獲此錯誤
archiveObject.on('error', function(err) {
throw err
})
// 生成一個流,放入到body中
const stream = new Stream.PassThrough()
this.ctx.response.body = stream
// 將數據歸檔到流文件中
archiveObject.pipe(stream)
// 可追加格式 stream/string/buffer/file等一些列方式; 目前只測試追加string、buffer
// append a file from string
archiveObject.append('string cheese!', { name: 'file1.txt' })
// append a file from buffer
const buffer2 = Buffer.from('buff it!');
archiveObject.append(buffer2, { name: 'file2.txt' })
// 完成歸檔(即我們完成了附加文件,但流還需要完成)
// “close”、“end”或“finish”可能在調用此方法後立即被觸發,因此請預先向它們註冊
archiveObject.finalize()
//壓縮包名稱
let fileName = 'text.zip'
//設置header
this.ctx.set('Content-Type', 'application/x-zip')
this.ctx.set('Content-Disposition', `attachment; filename=${new Buffer(fileName).toString('binary')}`)
archiveObject.on('finish', function(err) {
this.ctx.response.end('binary')
})
}