index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. var path = require('path');
  3. var gutil = require('gulp-util');
  4. var through = require('through2');
  5. var chalk = require('chalk');
  6. var JSZip = require('jszip');
  7. module.exports = function (filename, opts) {
  8. if (!filename) {
  9. throw new gutil.PluginError('gulp-zip', chalk.blue('filename') + ' required');
  10. }
  11. opts = opts || {};
  12. opts.compress = typeof opts.compress === 'boolean' ? opts.compress : true;
  13. var firstFile;
  14. var zip = new JSZip();
  15. return through.obj(function (file, enc, cb) {
  16. if (file.isNull()) {
  17. cb();
  18. return;
  19. }
  20. if (file.isStream()) {
  21. cb(new gutil.PluginError('gulp-zip', 'Streaming not supported'));
  22. return;
  23. }
  24. if (!firstFile) {
  25. firstFile = file;
  26. }
  27. // because Windows...
  28. var pathname = file.relative.replace(/\\/g, '/');
  29. zip.file(pathname, file.contents, {
  30. date: file.stat ? file.stat.mtime : new Date(),
  31. createFolders: true
  32. });
  33. cb();
  34. }, function (cb) {
  35. if (!firstFile) {
  36. cb();
  37. return;
  38. }
  39. this.push(new gutil.File({
  40. cwd: firstFile.cwd,
  41. base: firstFile.base,
  42. path: path.join(firstFile.base, filename),
  43. contents: zip.generate({
  44. type: 'nodebuffer',
  45. compression: opts.compress ? 'DEFLATE' : 'STORE',
  46. comment: opts.comment
  47. })
  48. }));
  49. cb();
  50. });
  51. };