zip-stream.js 1.9 KB

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