11import path from 'path' ;
2- import { decodeNullUnicode } from './utils' ;
3-
4- const Unzip = require ( 'isomorphic-unzip' ) ;
5-
62import { enumZipEntries , readEntry } from '../zip-entries' ;
3+ import { decodeNullUnicode } from './utils' ;
74
85export class Zip {
96 file : string | File ;
10- unzip : any ;
117
128 constructor ( file : string | File ) {
139 this . file = typeof file === 'string' ? path . resolve ( file ) : file ;
14- this . unzip = new Unzip ( this . file ) ;
1510 }
1611
1712 /**
@@ -24,15 +19,7 @@ export class Zip {
2419 type : 'buffer' | 'blob' = 'buffer' ,
2520 ) {
2621 const decoded = regexps . map ( ( regex ) => decodeNullUnicode ( regex ) ) ;
27- return new Promise < Record < string , Buffer | Blob > > ( ( resolve , reject ) => {
28- this . unzip . getBuffer (
29- decoded ,
30- { type } ,
31- ( err : Error | null , buffers : Record < string , Buffer | Blob > ) => {
32- err ? reject ( err ) : resolve ( buffers ) ;
33- } ,
34- ) ;
35- } ) ;
22+ return this . readEntries ( decoded , type ) ;
3623 }
3724
3825 /**
@@ -42,15 +29,9 @@ export class Zip {
4229 */
4330 getEntry ( regex : RegExp | string , type : 'buffer' | 'blob' = 'buffer' ) {
4431 const decoded = decodeNullUnicode ( regex ) ;
45- return new Promise < Buffer | Blob | undefined > ( ( resolve , reject ) => {
46- this . unzip . getBuffer (
47- [ decoded ] ,
48- { type } ,
49- ( err : Error | null , buffers : Record < string , Buffer | Blob > ) => {
50- err ? reject ( err ) : resolve ( buffers [ decoded as any ] ) ;
51- } ,
52- ) ;
53- } ) ;
32+ return this . readEntries ( [ decoded ] , type ) . then (
33+ ( buffers ) => buffers [ decoded as any ] ,
34+ ) ;
5435 }
5536
5637 async getEntryFromHarmonyApp (
@@ -71,4 +52,40 @@ export class Zip {
7152 console . error ( 'Error in getEntryFromHarmonyApp:' , error ) ;
7253 }
7354 }
55+
56+ private async readEntries (
57+ decoded : Array < RegExp | string > ,
58+ type : 'buffer' | 'blob' ,
59+ ) : Promise < Record < string , Buffer | Blob > > {
60+ if ( typeof this . file !== 'string' ) {
61+ throw new Error ( 'Param error: [file] must be file path in Node.' ) ;
62+ }
63+
64+ const buffers : Record < string , Buffer | Blob > = { } ;
65+ await enumZipEntries ( this . file , async ( entry , zipFile ) => {
66+ if ( entry . fileName . endsWith ( '/' ) ) {
67+ return ;
68+ }
69+
70+ const entryName = decodeNullUnicode ( entry . fileName ) . toString ( ) ;
71+ const lowerEntryName = entryName . toLowerCase ( ) ;
72+ const matched = decoded . find ( ( pattern ) => {
73+ if ( typeof pattern === 'string' ) {
74+ return pattern === entryName || pattern === lowerEntryName ;
75+ }
76+ pattern . lastIndex = 0 ;
77+ return pattern . test ( lowerEntryName ) ;
78+ } ) ;
79+
80+ if ( ! matched ) {
81+ return ;
82+ }
83+
84+ const buffer = await readEntry ( entry , zipFile ) ;
85+ buffers [ matched as any ] =
86+ type === 'blob' ? new Blob ( [ buffer as any ] ) : buffer ;
87+ } ) ;
88+
89+ return buffers ;
90+ }
7491}
0 commit comments