zip.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const fs = require('fs');
  2. const path = require('path');
  3. const archiver = require('archiver');
  4. const packageJson = require('../package.json');
  5. const root = path.join(__dirname, '../');
  6. // create a file to stream archive data to.
  7. const output = fs.createWriteStream(path.join(root, `${packageJson.name}.zip`));
  8. const archive = archiver('zip', {
  9. zlib: { level: 9 }, // Sets the compression level.
  10. });
  11. // listen for all archive data to be written
  12. // 'close' event is fired only when a file descriptor is involved
  13. output.on('close', () => {
  14. console.log(archive.pointer() + ' total bytes');
  15. console.log(
  16. 'archiver has been finalized and the output file descriptor has closed.',
  17. );
  18. });
  19. // This event is fired when the data source is drained no matter what was the data source.
  20. // It is not part of this library but rather from the NodeJS Stream API.
  21. // @see: https://nodejs.org/api/stream.html#stream_event_end
  22. output.on('end', () => {
  23. console.log('Data has been drained');
  24. });
  25. // good practice to catch warnings (ie stat failures and other non-blocking errors)
  26. archive.on('warning', (err) => {
  27. if (err.code === 'ENOENT') {
  28. // log warning
  29. } else {
  30. // throw error
  31. throw err;
  32. }
  33. });
  34. // good practice to catch this error explicitly
  35. archive.on('error', (err) => {
  36. throw err;
  37. });
  38. // pipe archive data to the file
  39. archive.pipe(output);
  40. const fileJob = fs.readdirSync(root, {
  41. withFileTypes: true,
  42. encoding: 'utf-8',
  43. });
  44. fileJob.forEach((job) => {
  45. if (job.isFile()) {
  46. if (!['.DS_Store', `${packageJson.name}.zip`].includes(job.name)) {
  47. const file = path.join(root, job.name);
  48. archive.append(fs.createReadStream(file), { name: job.name });
  49. }
  50. } else if (job.isDirectory()) {
  51. const dir = path.join(root, `${job.name}/`);
  52. if (!['node_modules', 'example', '.git', '.zip'].includes(job.name)) {
  53. archive.directory(dir, job.name);
  54. }
  55. }
  56. });
  57. // append a file from stream
  58. // archive.directory(path.join(__dirname, '../config/'), 'config')
  59. // finalize the archive (ie we are done appending files but streams have to finish yet)
  60. // 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand
  61. archive.finalize();