JavaScript library for compressing and decompressing ZIP files in browsers, Node.js, and Deno with support for encryption, ZIP64, and web workers
npx @tessl/cli install tessl/npm-zip-js--zip-js@2.7.00
# @zip.js/zip.js
1
2
## Package Information
3
4
- **Package Name:** @zip.js/zip.js
5
- **Type:** Library
6
- **Language:** JavaScript/TypeScript
7
- **Installation:** `npm install @zip.js/zip.js`
8
9
## Overview
10
11
zip.js is a powerful JavaScript library for creating and reading ZIP files in browsers, Deno, and Node.js environments. It provides a comprehensive set of APIs for ZIP file manipulation with support for advanced features and optimal performance across different JavaScript runtime environments.
12
13
### Key Features
14
15
- **Multi-core compression** via web workers for improved performance
16
- **Large file support** with Zip64 format (files > 4GB)
17
- **Data encryption** using AES-256, AES-192, AES-128, and ZipCrypto algorithms
18
- **Split ZIP files** for handling size-constrained storage
19
- **Streaming operations** for memory-efficient processing of large archives
20
- **Multiple data sources** including Blob, ArrayBuffer, ReadableStream, HTTP ranges
21
- **Filesystem-like API** for complex ZIP manipulation scenarios
22
- **Native compression streams** support for optimal performance
23
- **Cross-platform compatibility** (browsers, Node.js, Deno, Bun)
24
25
## Core Imports
26
27
### ESM (Recommended)
28
29
```javascript
30
import {
31
ZipReader,
32
ZipWriter,
33
BlobReader,
34
BlobWriter,
35
TextReader,
36
TextWriter,
37
configure
38
} from "@zip.js/zip.js";
39
```
40
41
### CommonJS
42
43
```javascript
44
const {
45
ZipReader,
46
ZipWriter,
47
BlobReader,
48
BlobWriter,
49
TextReader,
50
TextWriter,
51
configure
52
} = require("@zip.js/zip.js");
53
```
54
55
### Alternative Entry Points
56
57
```javascript
58
// Full API with embedded codecs
59
import * as zip from "@zip.js/zip.js/lib/zip-full.js";
60
61
// Filesystem API
62
import { fs } from "@zip.js/zip.js/lib/zip-fs.js";
63
64
// No web workers
65
import * as zip from "@zip.js/zip.js/lib/zip-no-worker.js";
66
```
67
68
## Basic Usage
69
70
```javascript
71
import {
72
ZipReader,
73
ZipWriter,
74
BlobReader,
75
BlobWriter,
76
TextReader,
77
TextWriter
78
} from "@zip.js/zip.js";
79
80
// Create a ZIP file
81
const zipWriter = new ZipWriter(new BlobWriter("application/zip"));
82
await zipWriter.add("hello.txt", new TextReader("Hello World!"));
83
const zipBlob = await zipWriter.close();
84
85
// Read a ZIP file
86
const zipReader = new ZipReader(new BlobReader(zipBlob));
87
const entries = await zipReader.getEntries();
88
const text = await entries[0].getData(new TextWriter());
89
await zipReader.close();
90
console.log(text); // "Hello World!"
91
```
92
93
## Architecture
94
95
zip.js is designed with a modular architecture supporting different use cases and environments while maintaining optimal performance and memory efficiency.
96
97
### Core Components
98
99
**Core API (`@zip.js/zip.js`)**
100
- `ZipReader`/`ZipWriter` - Primary classes for ZIP operations
101
- Reader/Writer abstraction for different data sources/destinations
102
- Configurable web worker support for non-blocking operations
103
104
**Streaming API**
105
- `ZipReaderStream`/`ZipWriterStream` - Stream-based processing
106
- Memory-efficient handling of large files
107
- Pipeline-compatible with web streams
108
109
**Filesystem API (`@zip.js/zip.js/lib/zip-fs.js`)**
110
- `FS` class providing filesystem-like operations
111
- `ZipDirectoryEntry`/`ZipFileEntry` for hierarchical manipulation
112
- Import/export capabilities with multiple data formats
113
114
### Build Variants
115
116
- **Default build**: Web workers + compression streams
117
- **Full build** (`zip-full.js`): Embedded codecs, no external dependencies
118
- **No-worker builds**: Synchronous operation variants
119
- **Filesystem build** (`zip-fs.js`): High-level filesystem API
120
121
### Web Worker Architecture
122
123
zip.js uses web workers for non-blocking compression/decompression:
124
- Automatic worker management and load balancing
125
- Configurable worker count and termination timeout
126
- Fallback to main thread when workers unavailable
127
128
## Configuration
129
130
Global library configuration for web workers, compression, and codecs.
131
132
```typescript { .api }
133
function configure(configuration: Configuration): void;
134
135
interface Configuration extends WorkerConfiguration {
136
maxWorkers?: number;
137
terminateWorkerTimeout?: number;
138
workerScripts?: {
139
deflate?: string[];
140
inflate?: string[];
141
};
142
chunkSize?: number;
143
Deflate?: typeof ZipDeflate;
144
Inflate?: typeof ZipInflate;
145
CompressionStream?: typeof TransformStream;
146
DecompressionStream?: typeof TransformStream;
147
}
148
149
interface WorkerConfiguration {
150
useWebWorkers?: boolean;
151
useCompressionStream?: boolean;
152
}
153
```
154
155
**[Configuration Details](./configuration.md)**
156
157
## Data Input/Output
158
159
Classes for reading from and writing to different data sources and destinations.
160
161
### Reader Classes
162
163
```typescript { .api }
164
class Reader<Type> {
165
constructor(value: Type);
166
readonly readable: ReadableStream;
167
readonly size: number;
168
init?(): Promise<void>;
169
readUint8Array(index: number, length: number): Promise<Uint8Array>;
170
}
171
172
class TextReader extends Reader<string> {}
173
class BlobReader extends Reader<Blob> {}
174
class Data64URIReader extends Reader<string> {}
175
class Uint8ArrayReader extends Reader<Uint8Array> {}
176
class HttpReader extends Reader<string> {
177
constructor(url: string | URL, options?: HttpOptions);
178
}
179
class HttpRangeReader extends HttpReader {
180
constructor(url: string | URL, options?: HttpRangeOptions);
181
}
182
class SplitDataReader extends Reader<(Reader<unknown> | ReadableReader | ReadableStream)[]> {}
183
```
184
185
### Writer Classes
186
187
```typescript { .api }
188
class Writer<Type> {
189
readonly writable: WritableStream;
190
init?(size?: number): Promise<void>;
191
writeUint8Array(array: Uint8Array): Promise<void>;
192
getData(): Promise<Type>;
193
}
194
195
class TextWriter extends Writer<string> {
196
constructor(encoding?: string);
197
}
198
class BlobWriter {
199
constructor(mimeString?: string);
200
readonly writable: WritableStream;
201
init(): Promise<void>;
202
getData(): Promise<Blob>;
203
}
204
class Data64URIWriter extends Writer<string> {
205
constructor(mimeString?: string);
206
}
207
class Uint8ArrayWriter extends Writer<Uint8Array> {}
208
class SplitDataWriter {
209
constructor(
210
writerGenerator: AsyncGenerator<Writer<unknown> | WritableWriter | WritableStream, boolean>,
211
maxSize?: number
212
);
213
readonly writable: WritableStream;
214
init(): Promise<void>;
215
}
216
```
217
218
**[Data Input/Output Details](./data-io.md)**
219
220
## ZIP Reading
221
222
Reading and extracting from ZIP files.
223
224
```typescript { .api }
225
class ZipReader<Type> {
226
constructor(
227
reader: Reader<Type> | ReadableReader | ReadableStream | (Reader<unknown> | ReadableReader | ReadableStream)[],
228
options?: ZipReaderConstructorOptions
229
);
230
231
readonly comment: Uint8Array;
232
readonly prependedData?: Uint8Array;
233
readonly appendedData?: Uint8Array;
234
235
getEntries(options?: ZipReaderGetEntriesOptions): Promise<Entry[]>;
236
getEntriesGenerator(options?: ZipReaderGetEntriesOptions): AsyncGenerator<Entry, boolean>;
237
close(): Promise<void>;
238
}
239
240
type Entry = DirectoryEntry | FileEntry;
241
242
interface DirectoryEntry extends EntryMetaData {
243
directory: true;
244
getData?: undefined;
245
}
246
247
interface FileEntry extends EntryMetaData {
248
directory: false;
249
getData<Type>(
250
writer: Writer<Type> | WritableWriter | WritableStream | AsyncGenerator<Writer<unknown> | WritableWriter | WritableStream, boolean>,
251
options?: EntryGetDataOptions
252
): Promise<Type>;
253
arrayBuffer(options?: EntryGetDataOptions): Promise<ArrayBuffer>;
254
}
255
```
256
257
**[ZIP Reading Details](./reading.md)**
258
259
## ZIP Writing
260
261
Creating and modifying ZIP files.
262
263
```typescript { .api }
264
class ZipWriter<Type> {
265
constructor(
266
writer: Writer<Type> | WritableWriter | WritableStream | AsyncGenerator<Writer<unknown> | WritableWriter | WritableStream, boolean>,
267
options?: ZipWriterConstructorOptions
268
);
269
270
readonly hasCorruptedEntries?: boolean;
271
272
prependZip<ReaderType>(
273
reader: Reader<ReaderType> | ReadableReader | ReadableStream | (Reader<unknown> | ReadableReader | ReadableStream)[]
274
): Promise<void>;
275
276
add<ReaderType>(
277
filename: string,
278
reader?: Reader<ReaderType> | ReadableReader | ReadableStream | (Reader<unknown> | ReadableReader | ReadableStream)[],
279
options?: ZipWriterAddDataOptions
280
): Promise<EntryMetaData>;
281
282
remove(entry: Entry | string): boolean;
283
close(comment?: Uint8Array, options?: ZipWriterCloseOptions): Promise<Type>;
284
}
285
```
286
287
**[ZIP Writing Details](./writing.md)**
288
289
## Streaming API
290
291
Stream-based ZIP operations for efficient processing of large files.
292
293
```typescript { .api }
294
class ZipReaderStream<T> {
295
constructor(options?: ZipReaderConstructorOptions);
296
297
readonly readable: ReadableStream<Omit<Entry, "getData"> & { readable?: ReadableStream<Uint8Array> }>;
298
readonly writable: WritableStream<T>;
299
}
300
301
class ZipWriterStream {
302
constructor(options?: ZipWriterConstructorOptions);
303
304
readonly readable: ReadableStream<Uint8Array>;
305
readonly zipWriter: ZipWriter<unknown>;
306
307
transform<T>(path: string): { readable: ReadableStream<T>; writable: WritableStream<T> };
308
writable<T>(path: string): WritableStream<T>;
309
close(comment?: Uint8Array, options?: ZipWriterCloseOptions): Promise<unknown>;
310
}
311
```
312
313
**[Streaming API Details](./streaming.md)**
314
315
## Filesystem API
316
317
High-level filesystem-like operations for complex ZIP manipulation.
318
319
```typescript { .api }
320
const fs: {
321
FS: typeof FS;
322
ZipDirectoryEntry: typeof ZipDirectoryEntry;
323
ZipFileEntry: typeof ZipFileEntry;
324
};
325
326
class FS extends ZipDirectoryEntry {
327
readonly root: ZipDirectoryEntry;
328
329
remove(entry: ZipEntry): void;
330
move(entry: ZipEntry, destination: ZipDirectoryEntry): void;
331
find(fullname: string): ZipEntry | undefined;
332
getById(id: number): ZipEntry | undefined;
333
}
334
```
335
336
**[Filesystem API Details](./filesystem.md)**
337
338
## Utilities
339
340
```typescript { .api }
341
function getMimeType(fileExtension: string): string;
342
function terminateWorkers(): Promise<void>;
343
function initShimAsyncCodec(
344
library: EventBasedZipLibrary,
345
constructorOptions: unknown | null,
346
registerDataHandler: registerDataHandler
347
): ZipLibrary;
348
```
349
350
## Error Constants
351
352
```typescript { .api }
353
const ERR_HTTP_RANGE: string;
354
const ERR_BAD_FORMAT: string;
355
const ERR_EOCDR_NOT_FOUND: string;
356
const ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND: string;
357
const ERR_CENTRAL_DIRECTORY_NOT_FOUND: string;
358
const ERR_LOCAL_FILE_HEADER_NOT_FOUND: string;
359
const ERR_EXTRAFIELD_ZIP64_NOT_FOUND: string;
360
const ERR_ENCRYPTED: string;
361
const ERR_UNSUPPORTED_ENCRYPTION: string;
362
const ERR_UNSUPPORTED_COMPRESSION: string;
363
const ERR_INVALID_SIGNATURE: string;
364
const ERR_INVALID_UNCOMPRESSED_SIZE: string;
365
const ERR_INVALID_PASSWORD: string;
366
const ERR_DUPLICATED_NAME: string;
367
const ERR_INVALID_COMMENT: string;
368
const ERR_INVALID_ENTRY_NAME: string;
369
const ERR_INVALID_ENTRY_COMMENT: string;
370
const ERR_INVALID_VERSION: string;
371
const ERR_INVALID_EXTRAFIELD_TYPE: string;
372
const ERR_INVALID_EXTRAFIELD_DATA: string;
373
const ERR_INVALID_ENCRYPTION_STRENGTH: string;
374
const ERR_UNSUPPORTED_FORMAT: string;
375
const ERR_SPLIT_ZIP_FILE: string;
376
const ERR_OVERLAPPING_ENTRY: string;
377
const ERR_ITERATOR_COMPLETED_TOO_SOON: string;
378
const ERR_UNDEFINED_UNCOMPRESSED_SIZE: string;
379
const ERR_WRITER_NOT_INITIALIZED: string;
380
const ERR_ZIP_NOT_EMPTY: string;
381
```
382
383
## Types
384
385
### EntryMetaData
386
387
```typescript { .api }
388
interface EntryMetaData {
389
offset: number;
390
filename: string;
391
rawFilename: Uint8Array;
392
filenameUTF8: boolean;
393
directory: boolean;
394
executable: boolean;
395
encrypted: boolean;
396
zipCrypto: boolean;
397
compressedSize: number;
398
uncompressedSize: number;
399
lastModDate: Date;
400
lastAccessDate?: Date;
401
creationDate?: Date;
402
rawLastModDate: number | bigint;
403
rawLastAccessDate?: number | bigint;
404
rawCreationDate?: number | bigint;
405
comment: string;
406
rawComment: Uint8Array;
407
commentUTF8: boolean;
408
signature: number;
409
extraField?: Map<number, { type: number; data: Uint8Array }>;
410
rawExtraField: Uint8Array;
411
zip64: boolean;
412
version: number;
413
versionMadeBy: number;
414
msDosCompatible: boolean;
415
internalFileAttributes: number;
416
externalFileAttributes: number;
417
diskNumberStart: number;
418
compressionMethod: number;
419
}
420
```
421
422
### HTTP Options
423
424
```typescript { .api }
425
interface HttpOptions extends HttpRangeOptions {
426
useRangeHeader?: boolean;
427
forceRangeRequests?: boolean;
428
preventHeadRequest?: boolean;
429
combineSizeEocd?: boolean;
430
}
431
432
interface HttpRangeOptions {
433
useXHR?: boolean;
434
headers?: Iterable<[string, string]> | Map<string, string>;
435
}
436
```
437
438
### Reader/Writer Interfaces
439
440
```typescript { .api }
441
interface Initializable {
442
init?(): Promise<void>;
443
}
444
445
interface ReadableReader {
446
readable: ReadableStream;
447
}
448
449
interface WritableWriter {
450
writable: WritableStream;
451
maxSize?: number;
452
}
453
```
454
455
### Event-based Codec Interfaces
456
457
```typescript { .api }
458
interface EventBasedZipLibrary {
459
Deflate: typeof EventBasedCodec;
460
Inflate: typeof EventBasedCodec;
461
}
462
463
interface ZipLibrary {
464
Deflate: typeof ZipDeflate;
465
Inflate: typeof ZipInflate;
466
}
467
468
interface registerDataHandler {
469
(codec: EventBasedCodec, onData: dataHandler): void;
470
}
471
472
interface dataHandler {
473
(data: Uint8Array): void;
474
}
475
```
476
477
### Option Interfaces
478
479
```typescript { .api }
480
interface ZipReaderConstructorOptions extends ZipReaderOptions, GetEntriesOptions, WorkerConfiguration {
481
extractPrependedData?: boolean;
482
extractAppendedData?: boolean;
483
}
484
485
interface ZipReaderGetEntriesOptions extends GetEntriesOptions, EntryOnprogressOptions {}
486
487
interface GetEntriesOptions {
488
filenameEncoding?: string;
489
commentEncoding?: string;
490
decodeText?(value: Uint8Array, encoding: string): string | undefined;
491
}
492
493
interface ZipReaderOptions {
494
checkPasswordOnly?: boolean;
495
checkSignature?: boolean;
496
checkOverlappingEntry?: boolean;
497
checkOverlappingEntryOnly?: boolean;
498
password?: string;
499
passThrough?: boolean;
500
rawPassword?: Uint8Array;
501
signal?: AbortSignal;
502
preventClose?: boolean;
503
transferStreams?: boolean;
504
}
505
506
interface EntryGetDataOptions extends EntryDataOnprogressOptions, ZipReaderOptions, WorkerConfiguration {}
507
508
interface ZipWriterConstructorOptions {
509
zip64?: boolean;
510
preventClose?: boolean;
511
level?: number;
512
bufferedWrite?: boolean;
513
keepOrder?: boolean;
514
password?: string;
515
rawPassword?: Uint8Array;
516
encryptionStrength?: 1 | 2 | 3;
517
signal?: AbortSignal;
518
lastModDate?: Date;
519
lastAccessDate?: Date;
520
creationDate?: Date;
521
extendedTimestamp?: boolean;
522
zipCrypto?: boolean;
523
version?: number;
524
versionMadeBy?: number;
525
useUnicodeFileNames?: boolean;
526
dataDescriptor?: boolean;
527
dataDescriptorSignature?: boolean;
528
msDosCompatible?: boolean;
529
externalFileAttributes?: number;
530
internalFileAttributes?: number;
531
supportZip64SplitFile?: boolean;
532
usdz?: boolean;
533
passThrough?: boolean;
534
encrypted?: boolean;
535
offset?: number;
536
compressionMethod?: number;
537
encodeText?(text: string): Uint8Array | undefined;
538
}
539
540
interface ZipWriterAddDataOptions extends ZipWriterConstructorOptions, EntryDataOnprogressOptions, WorkerConfiguration {
541
directory?: boolean;
542
executable?: boolean;
543
comment?: string;
544
extraField?: Map<number, Uint8Array>;
545
uncompressedSize?: number;
546
signature?: number;
547
}
548
549
interface ZipWriterCloseOptions extends EntryOnprogressOptions {
550
zip64?: boolean;
551
preventClose?: boolean;
552
}
553
554
interface EntryDataOnprogressOptions {
555
onstart?(total: number): Promise<void> | undefined;
556
onprogress?(progress: number, total: number): Promise<void> | undefined;
557
onend?(computedSize: number): Promise<void> | undefined;
558
}
559
560
interface EntryOnprogressOptions {
561
onprogress?(progress: number, total: number, entry: EntryMetaData): Promise<void> | undefined;
562
}
563
564
declare class SyncCodec {
565
append(data: Uint8Array): Uint8Array;
566
}
567
568
declare class ZipDeflate extends SyncCodec {
569
flush(): Uint8Array;
570
}
571
572
declare class ZipInflate extends SyncCodec {
573
flush(): void;
574
}
575
576
declare class EventBasedCodec {
577
push(data: Uint8Array): void;
578
ondata(data?: Uint8Array): void;
579
}
580
```