zipFile.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.ZipFile = void 0;
  6. var _zipBundle = require("../zipBundle");
  7. /**
  8. * Copyright (c) Microsoft Corporation.
  9. *
  10. * Licensed under the Apache License, Version 2.0 (the "License");
  11. * you may not use this file except in compliance with the License.
  12. * You may obtain a copy of the License at
  13. *
  14. * http://www.apache.org/licenses/LICENSE-2.0
  15. *
  16. * Unless required by applicable law or agreed to in writing, software
  17. * distributed under the License is distributed on an "AS IS" BASIS,
  18. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. * See the License for the specific language governing permissions and
  20. * limitations under the License.
  21. */
  22. class ZipFile {
  23. constructor(fileName) {
  24. this._fileName = void 0;
  25. this._zipFile = void 0;
  26. this._entries = new Map();
  27. this._openedPromise = void 0;
  28. this._fileName = fileName;
  29. this._openedPromise = this._open();
  30. }
  31. async _open() {
  32. await new Promise((fulfill, reject) => {
  33. _zipBundle.yauzl.open(this._fileName, {
  34. autoClose: false
  35. }, (e, z) => {
  36. if (e) {
  37. reject(e);
  38. return;
  39. }
  40. this._zipFile = z;
  41. this._zipFile.on('entry', entry => {
  42. this._entries.set(entry.fileName, entry);
  43. });
  44. this._zipFile.on('end', fulfill);
  45. });
  46. });
  47. }
  48. async entries() {
  49. await this._openedPromise;
  50. return [...this._entries.keys()];
  51. }
  52. async read(entryPath) {
  53. await this._openedPromise;
  54. const entry = this._entries.get(entryPath);
  55. if (!entry) throw new Error(`${entryPath} not found in file ${this._fileName}`);
  56. return new Promise((resolve, reject) => {
  57. this._zipFile.openReadStream(entry, (error, readStream) => {
  58. if (error || !readStream) {
  59. reject(error || 'Entry not found');
  60. return;
  61. }
  62. const buffers = [];
  63. readStream.on('data', data => buffers.push(data));
  64. readStream.on('end', () => resolve(Buffer.concat(buffers)));
  65. });
  66. });
  67. }
  68. close() {
  69. var _this$_zipFile;
  70. (_this$_zipFile = this._zipFile) === null || _this$_zipFile === void 0 ? void 0 : _this$_zipFile.close();
  71. }
  72. }
  73. exports.ZipFile = ZipFile;