ZipReader.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const StreamZip = require('node-stream-zip');
  2. class ZipReader {
  3. constructor() {
  4. this.zip = null;
  5. }
  6. checkState() {
  7. if (!this.zip)
  8. throw new Error('Zip closed');
  9. }
  10. async open(zipFile) {
  11. if (this.zip)
  12. throw new Error('Zip file is already open');
  13. const zip = new StreamZip.async({file: zipFile});
  14. this.zipEntries = await zip.entries();
  15. this.zip = zip;
  16. }
  17. get entries() {
  18. this.checkState();
  19. return this.zipEntries;
  20. }
  21. async extractToBuf(entryFilePath) {
  22. this.checkState();
  23. return await this.zip.entryData(entryFilePath);
  24. }
  25. async extractToFile(entryFilePath, outputFile) {
  26. this.checkState();
  27. await this.zip.extract(entryFilePath, outputFile);
  28. }
  29. async extractAllToDir(outputDir) {
  30. this.checkState();
  31. await this.zip.extract(null, outputDir);
  32. }
  33. close() {
  34. if (this.zip) {
  35. this.zip.close();
  36. this.zip = null;
  37. this.zipEntries = null;
  38. }
  39. }
  40. }
  41. module.exports = ZipReader;