zip.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. const fs = require('fs')
  2. const path = require('path')
  3. const archiver = require('archiver')
  4. const dayjs = require('dayjs')
  5. /**
  6. * 说明:压缩后的命名格式:RESIST_2023-09-09 23_40.zip
  7. */
  8. const currentDateTime = dayjs().format('YYYY-MM-DD HH_mm')
  9. /**
  10. * 说明:输出的路径及文件名
  11. * tips:是相对与package.json的路径,因为是在package.json中调用的scripts/zip.js
  12. */
  13. const file_path = `./dist/RESIST_${currentDateTime}.zip`
  14. // 检查文件是否存在,是的话则删除后再压缩
  15. if (fs.existsSync(file_path)) {
  16. console.log(`${file_path} already exists. Deleting the file...`)
  17. fs.unlinkSync(file_path)
  18. }
  19. const output = fs.createWriteStream(file_path)
  20. const archive = archiver('zip', {
  21. zlib: { level: 9 }, // 设置压缩级别
  22. })
  23. output.on('close', function() {
  24. console.log(archive.pointer() + ' total bytes')
  25. console.log(`RESIST_${currentDateTime}.zip has been created successfully.`)
  26. })
  27. output.on('end', function() {
  28. console.log('Data has been drained')
  29. })
  30. archive.on('warning', function(err) {
  31. if (err.code === 'ENOENT') {
  32. console.warn(err)
  33. } else {
  34. throw err
  35. }
  36. })
  37. archive.on('error', function(err) {
  38. throw err
  39. })
  40. // 将要压缩的文件夹(相对于此文件的路径)添加到压缩包,解压后的名字仍为RESIST
  41. archive.directory(path.join(__dirname, '../dist/RESIST'), 'RESIST')
  42. // 完成压缩并写入到文件流中
  43. archive.pipe(output)
  44. archive.finalize()