0
# Utility and Configuration
1
2
Static properties providing feature detection, version information, configuration options, and platform compatibility utilities for JSZip.
3
4
## Capabilities
5
6
### Version Information
7
8
Access the current JSZip library version.
9
10
```javascript { .api }
11
/**
12
* Current version of the JSZip library
13
*/
14
static version: string;
15
```
16
17
**Usage Examples:**
18
19
```javascript
20
import JSZip from "jszip";
21
22
console.log("JSZip version:", JSZip.version); // "3.10.1"
23
24
// Version-dependent feature checks
25
const [major, minor, patch] = JSZip.version.split('.').map(Number);
26
if (major >= 3 && minor >= 10) {
27
console.log("Modern JSZip version with latest features");
28
}
29
30
// Include version in generated ZIP comments
31
const zip = new JSZip();
32
zip.file("readme.txt", "Hello World");
33
const result = await zip.generateAsync({
34
type: "blob",
35
comment: `Generated with JSZip v${JSZip.version}`
36
});
37
```
38
39
### Feature Detection
40
41
Runtime detection of platform capabilities and supported features.
42
43
```javascript { .api }
44
/**
45
* Platform capability detection
46
*/
47
static support: JSZipSupport;
48
49
interface JSZipSupport {
50
/** ArrayBuffer support */
51
arraybuffer: boolean;
52
/** Uint8Array support */
53
uint8array: boolean;
54
/** Blob support (browser) */
55
blob: boolean;
56
/** Node.js Buffer support */
57
nodebuffer: boolean;
58
/** Node.js Readable stream support */
59
nodestream: boolean;
60
}
61
```
62
63
**Usage Examples:**
64
65
```javascript
66
import JSZip from "jszip";
67
68
// Check platform capabilities
69
console.log("Platform support:", JSZip.support);
70
71
// Conditional logic based on support
72
if (JSZip.support.blob) {
73
// Browser environment
74
const zip = new JSZip();
75
zip.file("test.txt", "Hello");
76
const blob = await zip.generateAsync({type: "blob"});
77
console.log("Generated as Blob");
78
} else if (JSZip.support.nodebuffer) {
79
// Node.js environment
80
const zip = new JSZip();
81
zip.file("test.txt", "Hello");
82
const buffer = await zip.generateAsync({type: "nodebuffer"});
83
console.log("Generated as Buffer");
84
}
85
86
// Feature-based format selection
87
function getBestOutputFormat() {
88
if (JSZip.support.uint8array) {
89
return "uint8array";
90
} else if (JSZip.support.arraybuffer) {
91
return "arraybuffer";
92
} else {
93
return "array";
94
}
95
}
96
97
const zip = new JSZip();
98
const format = getBestOutputFormat();
99
const result = await zip.generateAsync({type: format});
100
101
// Input format validation
102
function canUseInput(inputType) {
103
switch (inputType) {
104
case 'blob':
105
return JSZip.support.blob;
106
case 'nodebuffer':
107
return JSZip.support.nodebuffer;
108
case 'uint8array':
109
return JSZip.support.uint8array;
110
case 'arraybuffer':
111
return JSZip.support.arraybuffer;
112
default:
113
return true; // string, array always supported
114
}
115
}
116
```
117
118
### Default Configuration
119
120
Access default options used for file operations.
121
122
```javascript { .api }
123
/**
124
* Default options for file operations
125
*/
126
static defaults: object;
127
```
128
129
**Usage Examples:**
130
131
```javascript
132
import JSZip from "jszip";
133
134
// Inspect default settings
135
console.log("Default options:", JSZip.defaults);
136
// Typical output:
137
// {
138
// base64: false,
139
// binary: false,
140
// dir: false,
141
// createFolders: true,
142
// date: null,
143
// compression: null,
144
// compressionOptions: null,
145
// comment: null,
146
// unixPermissions: null,
147
// dosPermissions: null
148
// }
149
150
// Understand default behavior
151
const zip = new JSZip();
152
153
// These two calls are equivalent due to defaults
154
zip.file("text1.txt", "Hello", {});
155
zip.file("text2.txt", "Hello", {
156
base64: false,
157
binary: false,
158
createFolders: true,
159
date: null
160
});
161
162
// Defaults help with consistent behavior
163
function addTextFile(zip, path, content) {
164
// Uses defaults: createFolders=true, binary=false, etc.
165
return zip.file(path, content);
166
}
167
168
function addBinaryFile(zip, path, data) {
169
// Override defaults for binary data
170
return zip.file(path, data, {
171
binary: true, // Override default of false
172
base64: false // Use default
173
});
174
}
175
```
176
177
### External Dependencies
178
179
Access external library dependencies and configuration.
180
181
```javascript { .api }
182
/**
183
* External dependencies configuration
184
*/
185
static external: {
186
Promise: PromiseConstructorLike;
187
};
188
```
189
190
**Usage Examples:**
191
192
```javascript
193
import JSZip from "jszip";
194
195
// Check Promise implementation
196
console.log("Promise implementation:", JSZip.external.Promise);
197
198
// JSZip uses native Promise if available, or lie polyfill
199
const isNativePromise = JSZip.external.Promise === window.Promise ||
200
JSZip.external.Promise === global.Promise;
201
202
console.log("Using native Promise:", isNativePromise);
203
204
// Custom Promise implementation (advanced usage)
205
// Note: This is typically not needed as JSZip handles this automatically
206
if (typeof window !== 'undefined' && window.Promise) {
207
// Browser with native Promise
208
console.log("Browser environment with native Promise");
209
} else if (typeof global !== 'undefined' && global.Promise) {
210
// Node.js with native Promise
211
console.log("Node.js environment with native Promise");
212
} else {
213
// Polyfilled environment
214
console.log("Using Promise polyfill");
215
}
216
217
// All JSZip async operations use this Promise implementation
218
const zip = new JSZip();
219
zip.file("test.txt", "Hello");
220
221
// This returns JSZip.external.Promise instance
222
const promise = zip.generateAsync({type: "string"});
223
console.log("Is JSZip Promise:", promise instanceof JSZip.external.Promise);
224
```
225
226
## Utility Functions
227
228
Access instance-level utility methods for ZIP manipulation.
229
230
### Clone Operation
231
232
Create deep copies of JSZip instances.
233
234
```javascript { .api }
235
/**
236
* Create a deep copy of the JSZip instance
237
* @returns New JSZip instance with copied files and settings
238
*/
239
clone(): JSZip;
240
```
241
242
**Usage Examples:**
243
244
```javascript
245
const originalZip = new JSZip();
246
originalZip.file("readme.txt", "Original content");
247
originalZip.file("data.json", JSON.stringify({version: 1}));
248
249
// Create a copy
250
const clonedZip = originalZip.clone();
251
252
// Modify the clone without affecting original
253
clonedZip.file("readme.txt", "Modified content");
254
clonedZip.file("new-file.txt", "Additional content");
255
256
// Original remains unchanged
257
const originalContent = await originalZip.file("readme.txt").async("string");
258
console.log("Original:", originalContent); // "Original content"
259
260
const clonedContent = await clonedZip.file("readme.txt").async("string");
261
console.log("Cloned:", clonedContent); // "Modified content"
262
263
// Different use case: template ZIP
264
const templateZip = new JSZip();
265
templateZip.file("template.html", "<html>{{content}}</html>");
266
templateZip.file("styles.css", "body { margin: 0; }");
267
268
// Create variations from template
269
const userZip1 = templateZip.clone();
270
userZip1.file("content.txt", "User 1 content");
271
272
const userZip2 = templateZip.clone();
273
userZip2.file("content.txt", "User 2 content");
274
275
// Generate separate ZIP files
276
const zip1 = await userZip1.generateAsync({type: "blob"});
277
const zip2 = await userZip2.generateAsync({type: "blob"});
278
```
279
280
## Platform Detection Utilities
281
282
Helper patterns for detecting and handling different JavaScript environments.
283
284
**Usage Examples:**
285
286
```javascript
287
import JSZip from "jszip";
288
289
// Environment detection helper
290
function getEnvironment() {
291
if (typeof window !== 'undefined') {
292
return 'browser';
293
} else if (typeof global !== 'undefined' && global.process) {
294
return 'node';
295
} else {
296
return 'unknown';
297
}
298
}
299
300
// Platform-appropriate file handling
301
async function saveZipFile(zip, filename) {
302
const env = getEnvironment();
303
304
if (env === 'browser') {
305
// Browser: use Blob and download
306
const blob = await zip.generateAsync({type: "blob"});
307
const url = URL.createObjectURL(blob);
308
const a = document.createElement('a');
309
a.href = url;
310
a.download = filename;
311
a.click();
312
URL.revokeObjectURL(url);
313
314
} else if (env === 'node') {
315
// Node.js: use Buffer and fs
316
const fs = require('fs');
317
const buffer = await zip.generateAsync({type: "nodebuffer"});
318
fs.writeFileSync(filename, buffer);
319
320
} else {
321
// Fallback: use array format
322
const array = await zip.generateAsync({type: "array"});
323
console.log("Generated ZIP as number array:", array.length, "bytes");
324
}
325
}
326
327
// Feature-based format selection
328
function selectBestFormat(purpose) {
329
const support = JSZip.support;
330
331
switch (purpose) {
332
case 'download':
333
return support.blob ? 'blob' : 'arraybuffer';
334
335
case 'upload':
336
return support.arraybuffer ? 'arraybuffer' : 'array';
337
338
case 'storage':
339
return support.nodebuffer ? 'nodebuffer' :
340
support.uint8array ? 'uint8array' : 'array';
341
342
case 'processing':
343
return support.uint8array ? 'uint8array' : 'array';
344
345
default:
346
return 'string';
347
}
348
}
349
350
// Cross-platform ZIP loading
351
async function loadZipFromSource(source) {
352
let zipData;
353
354
if (typeof source === 'string') {
355
// URL or file path
356
if (source.startsWith('http')) {
357
// URL - use fetch
358
const response = await fetch(source);
359
zipData = await response.arrayBuffer();
360
} else {
361
// File path - Node.js only
362
const fs = require('fs');
363
zipData = fs.readFileSync(source);
364
}
365
} else if (source instanceof File) {
366
// Browser File object
367
zipData = await source.arrayBuffer();
368
} else {
369
// Direct data
370
zipData = source;
371
}
372
373
return await JSZip.loadAsync(zipData);
374
}
375
```
376
377
## Configuration Best Practices
378
379
Recommended patterns for configuring JSZip based on use cases.
380
381
**Usage Examples:**
382
383
```javascript
384
// Web application configuration
385
const webConfig = {
386
// Prefer blob for downloads
387
outputFormat: JSZip.support.blob ? 'blob' : 'arraybuffer',
388
389
// Enable compression for bandwidth
390
compression: 'DEFLATE',
391
compressionOptions: { level: 6 },
392
393
// Browser-friendly settings
394
platform: 'DOS',
395
createFolders: true
396
};
397
398
// Node.js application configuration
399
const nodeConfig = {
400
// Use Buffer for file system operations
401
outputFormat: 'nodebuffer',
402
403
// Higher compression for storage
404
compression: 'DEFLATE',
405
compressionOptions: { level: 9 },
406
407
// Unix-style attributes
408
platform: 'UNIX',
409
createFolders: true
410
};
411
412
// Mobile/performance-optimized configuration
413
const mobileConfig = {
414
// Faster format for mobile
415
outputFormat: JSZip.support.uint8array ? 'uint8array' : 'array',
416
417
// Lower compression for speed
418
compression: 'DEFLATE',
419
compressionOptions: { level: 1 },
420
421
// Skip CRC checks for speed
422
checkCRC32: false,
423
streamFiles: true
424
};
425
426
// Apply configuration based on environment
427
function createOptimizedZip() {
428
const zip = new JSZip();
429
430
// Set appropriate defaults based on environment
431
if (getEnvironment() === 'browser') {
432
zip.generateConfig = webConfig;
433
} else if (getEnvironment() === 'node') {
434
zip.generateConfig = nodeConfig;
435
} else {
436
zip.generateConfig = mobileConfig;
437
}
438
439
return zip;
440
}
441
```