zip.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. const fs = require('fs');
  2. const path = require("path");
  3. const archiver = require('archiver')
  4. // 获取当前命令行上下文路径
  5. const currentDirectory = process.cwd();
  6. console.log(`----------------------------`)
  7. console.log(`正在准备打包为zip压缩文件...`)
  8. const distJoinPath = path.join(currentDirectory, '/zip/');
  9. if(!fs.existsSync(distJoinPath)) {
  10. console.log(`zip文件夹不存在,准备创建...`)
  11. fs.mkdir(distJoinPath, (err)=>{
  12. if(err){
  13. console.log('zip文件夹创建失败')
  14. }else{
  15. console.log('zip文件夹创建成功')
  16. }
  17. })
  18. }
  19. // 创建文件输出流
  20. console.log(`初始化zip文件流...`)
  21. const distZipPath = path.join(currentDirectory, '/zip/dist.zip');
  22. let output = fs.createWriteStream(distZipPath)
  23. let archive = archiver('zip', {
  24. zlib: { level: 9 } // 设置压缩级别
  25. })
  26. // 文件输出流结束
  27. output.on('close', function() {
  28. console.log('打包完成,zip文件位于zip文件夹下,/zip/dist.zip')
  29. })
  30. // 数据源是否耗尽
  31. output.on('end', function() {
  32. console.log('数据源已耗尽')
  33. })
  34. // 存档警告
  35. archive.on('warning', function(err) {
  36. if (err.code === 'ENOENT') {
  37. console.warn('stat故障和其他非阻塞错误')
  38. } else {
  39. throw err
  40. }
  41. })
  42. // 存档出错
  43. archive.on('error', function(err) {
  44. throw err
  45. })
  46. // 通过管道方法将输出流存档到文件
  47. archive.pipe(output)
  48. console.log(`正在将dist文件夹到zip中...`)
  49. const distPath = path.join(currentDirectory, '/dist/');
  50. //打包dist里面的所有文件和目录
  51. archive.directory(distPath, false)
  52. //完成归档
  53. archive.finalize()