zip-stream.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. const events = require('events');
  2. const JSZip = require('jszip');
  3. const StreamBuf = require('./stream-buf');
  4. const {stringToBuffer} = require('./browser-buffer-encode');
  5. // =============================================================================
  6. // The ZipWriter class
  7. // Packs streamed data into an output zip stream
  8. class ZipWriter extends events.EventEmitter {
  9. constructor(options) {
  10. super();
  11. this.options = Object.assign(
  12. {
  13. type: 'nodebuffer',
  14. compression: 'DEFLATE',
  15. },
  16. options
  17. );
  18. this.zip = new JSZip();
  19. this.stream = new StreamBuf();
  20. }
  21. append(data, options) {
  22. if (options.hasOwnProperty('base64') && options.base64) {
  23. this.zip.file(options.name, data, {base64: true});
  24. } else {
  25. // https://www.npmjs.com/package/process
  26. if (process.browser && typeof data === 'string') {
  27. // use TextEncoder in browser
  28. data = stringToBuffer(data);
  29. }
  30. this.zip.file(options.name, data);
  31. }
  32. }
  33. async finalize() {
  34. const content = await this.zip.generateAsync(this.options);
  35. this.stream.end(content);
  36. this.emit('finish');
  37. }
  38. // ==========================================================================
  39. // Stream.Readable interface
  40. read(size) {
  41. return this.stream.read(size);
  42. }
  43. setEncoding(encoding) {
  44. return this.stream.setEncoding(encoding);
  45. }
  46. pause() {
  47. return this.stream.pause();
  48. }
  49. resume() {
  50. return this.stream.resume();
  51. }
  52. isPaused() {
  53. return this.stream.isPaused();
  54. }
  55. pipe(destination, options) {
  56. return this.stream.pipe(destination, options);
  57. }
  58. unpipe(destination) {
  59. return this.stream.unpipe(destination);
  60. }
  61. unshift(chunk) {
  62. return this.stream.unshift(chunk);
  63. }
  64. wrap(stream) {
  65. return this.stream.wrap(stream);
  66. }
  67. }
  68. // =============================================================================
  69. module.exports = {
  70. ZipWriter,
  71. };