ZipReader.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const StreamUnzip = 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, zipEntries = true) {
  11. if (this.zip)
  12. throw new Error('Zip file is already open');
  13. const zip = new StreamUnzip.async({file: zipFile, skipEntryNameValidation: true});
  14. if (zipEntries)
  15. this.zipEntries = await zip.entries();
  16. this.zip = zip;
  17. }
  18. get entries() {
  19. this.checkState();
  20. return this.zipEntries;
  21. }
  22. async extractToBuf(entryFilePath) {
  23. this.checkState();
  24. return await this.zip.entryData(entryFilePath);
  25. }
  26. async extractToFile(entryFilePath, outputFile) {
  27. this.checkState();
  28. await this.zip.extract(entryFilePath, outputFile);
  29. }
  30. async extractAllToDir(outputDir) {
  31. this.checkState();
  32. await this.zip.extract(null, outputDir);
  33. }
  34. async close() {
  35. if (this.zip) {
  36. await this.zip.close();
  37. this.zip = null;
  38. this.zipEntries = undefined;
  39. }
  40. }
  41. }
  42. module.exports = ZipReader;