0
# ZIP Loading
1
2
Load and parse existing ZIP files from various input sources with validation, error handling, and customizable parsing options. Supports multiple input formats and provides comprehensive ZIP structure analysis.
3
4
## Capabilities
5
6
### Static Loading
7
8
Load ZIP data using the static method to create a new JSZip instance.
9
10
```javascript { .api }
11
/**
12
* Load ZIP data and create new JSZip instance (static method)
13
* @param content - ZIP data in various formats
14
* @param options - Loading options for parsing behavior
15
* @returns Promise resolving to new JSZip instance
16
*/
17
static loadAsync(content: InputFileFormat, options?: JSZipLoadOptions): Promise<JSZip>;
18
```
19
20
**Usage Examples:**
21
22
```javascript
23
import JSZip from "jszip";
24
25
// Load from file input (browser)
26
const fileInput = document.getElementById('zipFile');
27
const file = fileInput.files[0];
28
const zip = await JSZip.loadAsync(file);
29
30
// Load from URL fetch (browser/Node.js)
31
const response = await fetch('https://example.com/archive.zip');
32
const arrayBuffer = await response.arrayBuffer();
33
const zip = await JSZip.loadAsync(arrayBuffer);
34
35
// Load from Node.js Buffer
36
import fs from 'fs';
37
const buffer = fs.readFileSync('archive.zip');
38
const zip = await JSZip.loadAsync(buffer);
39
40
// Load from Base64 string
41
const base64Data = "UEsDBAoAAAAAAIdYzlQAAA..."; // Base64 ZIP data
42
const zip = await JSZip.loadAsync(base64Data, {base64: true});
43
44
// Load with options
45
const zip = await JSZip.loadAsync(zipData, {
46
checkCRC32: true,
47
createFolders: true
48
});
49
```
50
51
### Instance Loading
52
53
Load ZIP data into an existing JSZip instance.
54
55
```javascript { .api }
56
/**
57
* Load ZIP data into existing JSZip instance
58
* @param data - ZIP data in various formats
59
* @param options - Loading options for parsing behavior
60
* @returns Promise resolving to the same JSZip instance
61
*/
62
loadAsync(data: InputFileFormat, options?: JSZipLoadOptions): Promise<JSZip>;
63
```
64
65
**Usage Examples:**
66
67
```javascript
68
const zip = new JSZip();
69
70
// Add some initial files
71
zip.file("readme.txt", "Initial content");
72
73
// Load additional ZIP data into the same instance
74
await zip.loadAsync(additionalZipData);
75
76
// The instance now contains both initial files and loaded files
77
console.log(Object.keys(zip.files)); // Shows all files
78
79
// Load with custom options
80
await zip.loadAsync(zipBuffer, {
81
checkCRC32: false, // Skip CRC validation for speed
82
createFolders: false // Don't create folder entries
83
});
84
```
85
86
## Input Formats
87
88
Various data formats that can be loaded as ZIP files.
89
90
```javascript { .api }
91
type InputFileFormat = InputByType[keyof InputByType] | Promise<InputByType[keyof InputByType]>;
92
93
interface InputByType {
94
base64: string;
95
string: string;
96
text: string;
97
binarystring: string;
98
array: number[];
99
uint8array: Uint8Array;
100
arraybuffer: ArrayBuffer;
101
blob: Blob;
102
stream: NodeJS.ReadableStream;
103
}
104
```
105
106
**Usage Examples:**
107
108
```javascript
109
// String formats
110
const zipFromBase64 = await JSZip.loadAsync(base64String, {base64: true});
111
const zipFromBinary = await JSZip.loadAsync(binaryString);
112
113
// Binary formats
114
const zipFromArray = await JSZip.loadAsync(numberArray);
115
const zipFromUint8 = await JSZip.loadAsync(uint8Array);
116
const zipFromBuffer = await JSZip.loadAsync(arrayBuffer);
117
118
// Browser-specific
119
const zipFromBlob = await JSZip.loadAsync(blob);
120
121
// Node.js-specific
122
const zipFromStream = await JSZip.loadAsync(readableStream);
123
124
// Async input (Promise-wrapped)
125
const zipFromPromise = await JSZip.loadAsync(
126
fetch('archive.zip').then(r => r.arrayBuffer())
127
);
128
```
129
130
## Loading Options
131
132
Configure ZIP parsing behavior and validation settings.
133
134
```javascript { .api }
135
interface JSZipLoadOptions {
136
/** Set to true if input data is base64 encoded */
137
base64?: boolean;
138
/** Enable CRC32 checksum validation */
139
checkCRC32?: boolean;
140
/** Set to true for optimized binary string parsing */
141
optimizedBinaryString?: boolean;
142
/** Automatically create folder entries for file paths */
143
createFolders?: boolean;
144
/** Custom filename decoding function */
145
decodeFileName?: (bytes: string[] | Uint8Array | Buffer) => string;
146
}
147
```
148
149
**Usage Examples:**
150
151
```javascript
152
// Basic loading with validation
153
const zipWithValidation = await JSZip.loadAsync(zipData, {
154
checkCRC32: true // Validate file integrity
155
});
156
157
// Loading base64 data
158
const zipFromBase64 = await JSZip.loadAsync(base64String, {
159
base64: true
160
});
161
162
// Custom filename handling for non-UTF8 filenames
163
const zipWithCustomNames = await JSZip.loadAsync(zipData, {
164
decodeFileName: (bytes) => {
165
// Handle special encoding like CP437 or Shift-JIS
166
return customDecode(bytes);
167
}
168
});
169
170
// Performance-optimized loading
171
const zipFast = await JSZip.loadAsync(zipData, {
172
checkCRC32: false, // Skip CRC validation
173
createFolders: false, // Don't create folder objects
174
optimizedBinaryString: true
175
});
176
177
// Complete loading with all options
178
const zipComplete = await JSZip.loadAsync(zipData, {
179
base64: false,
180
checkCRC32: true,
181
createFolders: true,
182
optimizedBinaryString: false,
183
decodeFileName: (bytes) => {
184
// Convert bytes to UTF-8 string
185
return new TextDecoder('utf-8').decode(new Uint8Array(bytes));
186
}
187
});
188
```
189
190
## Post-Loading Operations
191
192
Work with the loaded ZIP structure and access file contents.
193
194
**Usage Examples:**
195
196
```javascript
197
// Load a ZIP file
198
const zip = await JSZip.loadAsync(zipData);
199
200
// Inspect the loaded structure
201
console.log("Files in ZIP:", Object.keys(zip.files));
202
203
// Check if specific files exist
204
if (zip.file("config.json")) {
205
const config = await zip.file("config.json").async("string");
206
console.log("Config:", JSON.parse(config));
207
}
208
209
// List all files and folders
210
zip.forEach((relativePath, file) => {
211
console.log(`${file.dir ? 'Folder' : 'File'}: ${relativePath}`);
212
console.log(` Date: ${file.date}`);
213
console.log(` Size: ${file._data ? file._data.uncompressedSize : 'unknown'}`);
214
});
215
216
// Extract all text files
217
const textFiles = zip.filter((relativePath, file) => {
218
return !file.dir && relativePath.endsWith('.txt');
219
});
220
221
for (const file of textFiles) {
222
const content = await file.async("string");
223
console.log(`Content of ${file.name}:`, content);
224
}
225
226
// Access file metadata
227
const someFile = zip.file("document.pdf");
228
if (someFile) {
229
console.log("File info:", {
230
name: someFile.name,
231
size: someFile._data?.uncompressedSize,
232
date: someFile.date,
233
comment: someFile.comment,
234
compression: someFile.options.compression
235
});
236
}
237
```
238
239
## Error Handling
240
241
Handle various loading errors and validation failures.
242
243
**Usage Examples:**
244
245
```javascript
246
try {
247
const zip = await JSZip.loadAsync(suspiciousData, {
248
checkCRC32: true
249
});
250
251
console.log("ZIP loaded successfully");
252
253
} catch (error) {
254
if (error.message.includes("CRC32")) {
255
console.error("ZIP file is corrupted (CRC mismatch)");
256
} else if (error.message.includes("signature")) {
257
console.error("Invalid ZIP file format");
258
} else if (error.message.includes("Zip64")) {
259
console.error("ZIP64 format not supported");
260
} else {
261
console.error("Unknown ZIP loading error:", error.message);
262
}
263
}
264
265
// Handle specific file extraction errors
266
try {
267
const zip = await JSZip.loadAsync(zipData);
268
const file = zip.file("protected.txt");
269
270
if (file) {
271
const content = await file.async("string");
272
}
273
274
} catch (error) {
275
if (error.message.includes("password")) {
276
console.error("File is password protected");
277
} else if (error.message.includes("compression")) {
278
console.error("Unsupported compression method");
279
} else {
280
console.error("File extraction error:", error.message);
281
}
282
}
283
```
284
285
## Security Considerations
286
287
Handle security-related concerns when loading ZIP files.
288
289
**Usage Examples:**
290
291
```javascript
292
// Check for zip-slip attacks
293
const zip = await JSZip.loadAsync(untrustedZipData);
294
295
zip.forEach((relativePath, file) => {
296
// Check for directory traversal
297
if (relativePath.includes('../') || relativePath.startsWith('/')) {
298
console.warn(`Suspicious path detected: ${relativePath}`);
299
return; // Skip this file
300
}
301
302
// Check original filename for traversal attempts
303
if (file.unsafeOriginalName && file.unsafeOriginalName !== relativePath) {
304
console.warn(`Path traversal attempt: ${file.unsafeOriginalName} -> ${relativePath}`);
305
}
306
});
307
308
// Limit extraction based on size
309
const MAX_EXTRACTED_SIZE = 100 * 1024 * 1024; // 100MB
310
let totalSize = 0;
311
312
for (const [path, file] of Object.entries(zip.files)) {
313
if (!file.dir) {
314
const size = file._data?.uncompressedSize || 0;
315
totalSize += size;
316
317
if (totalSize > MAX_EXTRACTED_SIZE) {
318
throw new Error("ZIP file too large to extract safely");
319
}
320
}
321
}
322
323
// Validate filenames
324
const SAFE_FILENAME_REGEX = /^[a-zA-Z0-9._\-\/]+$/;
325
326
zip.forEach((relativePath, file) => {
327
if (!SAFE_FILENAME_REGEX.test(relativePath)) {
328
console.warn(`Unsafe filename: ${relativePath}`);
329
}
330
});
331
```