You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. 'use strict';
  2. const path = require('path');
  3. const Vinyl = require('vinyl');
  4. const PluginError = require('plugin-error');
  5. const through = require('through2');
  6. const Yazl = require('yazl');
  7. const getStream = require('get-stream');
  8. module.exports = (filename, options) => {
  9. if (!filename) {
  10. throw new PluginError('gulp-zip', '`filename` required');
  11. }
  12. options = {
  13. compress: true,
  14. ...options
  15. };
  16. let firstFile;
  17. const zip = new Yazl.ZipFile();
  18. return through.obj((file, encoding, callback) => {
  19. if (!firstFile) {
  20. firstFile = file;
  21. }
  22. // Because Windows...
  23. const pathname = file.relative.replace(/\\/g, '/');
  24. if (!pathname) {
  25. callback();
  26. return;
  27. }
  28. if (file.isNull() && file.stat && file.stat.isDirectory && file.stat.isDirectory()) {
  29. zip.addEmptyDirectory(pathname, {
  30. mtime: options.modifiedTime || file.stat.mtime || new Date(),
  31. mode: file.stat.mode
  32. });
  33. } else {
  34. const stat = {
  35. compress: options.compress,
  36. mtime: options.modifiedTime || (file.stat ? file.stat.mtime : new Date()),
  37. mode: file.stat ? file.stat.mode : null
  38. };
  39. if (file.isStream()) {
  40. zip.addReadStream(file.contents, pathname, stat);
  41. }
  42. if (file.isBuffer()) {
  43. zip.addBuffer(file.contents, pathname, stat);
  44. }
  45. }
  46. callback();
  47. }, function (callback) {
  48. if (!firstFile) {
  49. callback();
  50. return;
  51. }
  52. (async () => {
  53. const data = await getStream.buffer(zip.outputStream);
  54. this.push(new Vinyl({
  55. cwd: firstFile.cwd,
  56. base: firstFile.base,
  57. path: path.join(firstFile.base, filename),
  58. contents: data
  59. }));
  60. callback();
  61. })();
  62. zip.end();
  63. });
  64. };