0
# File and Folder Operations
1
2
Core functionality for adding, retrieving, and managing files and folders within ZIP archives. Supports hierarchical folder structures, file metadata, and various data input formats.
3
4
## Capabilities
5
6
### File Management
7
8
Add, retrieve, or remove files from the ZIP archive with support for different data formats and file options.
9
10
```javascript { .api }
11
/**
12
* Add a file to the ZIP archive or retrieve existing file(s)
13
* @param path - File path within the ZIP
14
* @param data - File content (optional, for adding files)
15
* @param options - File options (optional)
16
* @returns JSZip instance (when adding), JSZipObject (when retrieving single file), or JSZipObject[] (when retrieving with RegExp)
17
*/
18
file(path: string): JSZipObject | null;
19
file(path: RegExp): JSZipObject[];
20
file<T extends InputType>(path: string, data: InputByType[T] | Promise<InputByType[T]>, options?: JSZipFileOptions): this;
21
file<T extends InputType>(path: string, data: null, options?: JSZipFileOptions & { dir: true }): this;
22
23
/**
24
* Remove a file or folder from the ZIP archive
25
* @param path - Path to remove
26
* @returns JSZip instance for chaining
27
*/
28
remove(path: string): JSZip;
29
```
30
31
**Usage Examples:**
32
33
```javascript
34
import JSZip from "jszip";
35
36
const zip = new JSZip();
37
38
// Add text file
39
zip.file("readme.txt", "This is a text file");
40
41
// Add binary data
42
zip.file("image.png", imageBuffer, {binary: true});
43
44
// Add file with metadata
45
zip.file("document.pdf", pdfData, {
46
date: new Date("2023-01-01"),
47
comment: "Important document",
48
compression: "DEFLATE"
49
});
50
51
// Retrieve a file
52
const textFile = zip.file("readme.txt");
53
if (textFile) {
54
const content = await textFile.async("string");
55
}
56
57
// Find files matching pattern
58
const imageFiles = zip.file(/\.(png|jpg|gif)$/i);
59
60
// Remove a file
61
zip.remove("unwanted.txt");
62
```
63
64
### Folder Management
65
66
Create, navigate, and manage folder structures within ZIP archives.
67
68
```javascript { .api }
69
/**
70
* Create a folder or navigate to an existing folder
71
* @param name - Folder name or path
72
* @returns New JSZip instance representing the folder, or null if not found
73
*/
74
folder(name: string): JSZip | null;
75
76
/**
77
* Find folders matching a pattern
78
* @param name - RegExp pattern to match folder names
79
* @returns Array of JSZipObject instances representing matching folders
80
*/
81
folder(name: RegExp): JSZipObject[];
82
```
83
84
**Usage Examples:**
85
86
```javascript
87
const zip = new JSZip();
88
89
// Create a folder
90
const imagesFolder = zip.folder("images");
91
92
// Add files to the folder
93
imagesFolder.file("logo.png", logoData, {base64: true});
94
imagesFolder.file("banner.jpg", bannerData, {binary: true});
95
96
// Create nested folders
97
const docsFolder = zip.folder("documents");
98
const publicDocs = docsFolder.folder("public");
99
publicDocs.file("readme.md", "# Public Documentation");
100
101
// Navigate to existing folder
102
const existingFolder = zip.folder("images");
103
if (existingFolder) {
104
existingFolder.file("new-image.png", newImageData);
105
}
106
107
// Find folders matching pattern
108
const allFolders = zip.folder(/.*docs.*/i);
109
```
110
111
### Iteration and Filtering
112
113
Iterate over files and apply filters to find specific content within the ZIP archive.
114
115
```javascript { .api }
116
/**
117
* Iterate over files at the current folder level
118
* @param callback - Function called for each file
119
*/
120
forEach(callback: (relativePath: string, file: JSZipObject) => void): void;
121
122
/**
123
* Filter files based on a predicate function
124
* @param predicate - Function to test each file
125
* @returns Array of JSZipObject instances matching the predicate
126
*/
127
filter(predicate: (relativePath: string, file: JSZipObject) => boolean): JSZipObject[];
128
```
129
130
**Usage Examples:**
131
132
```javascript
133
const zip = new JSZip();
134
135
// Add various files...
136
zip.file("readme.txt", "Documentation");
137
zip.file("data.json", JSON.stringify({key: "value"}));
138
zip.folder("images").file("logo.png", logoData);
139
140
// Iterate over all files
141
zip.forEach((relativePath, file) => {
142
console.log(`File: ${relativePath}, Size: ${file.name.length}`);
143
});
144
145
// Filter for text files
146
const textFiles = zip.filter((relativePath, file) => {
147
return relativePath.endsWith('.txt') || relativePath.endsWith('.md');
148
});
149
150
// Filter for files in specific folder
151
const imageFiles = zip.filter((relativePath, file) => {
152
return relativePath.startsWith('images/') && !file.dir;
153
});
154
155
// Filter by file size or date
156
const recentFiles = zip.filter((relativePath, file) => {
157
return file.date > new Date('2023-01-01');
158
});
159
```
160
161
### Instance Cloning
162
163
Create a deep copy of the JSZip instance with all files and settings.
164
165
```javascript { .api }
166
/**
167
* Create a deep copy of the JSZip instance
168
* @returns New JSZip instance with copied files and settings
169
*/
170
clone(): JSZip;
171
```
172
173
**Usage Examples:**
174
175
```javascript
176
const zip = new JSZip();
177
zip.file("readme.txt", "Hello World");
178
zip.file("data.json", JSON.stringify({key: "value"}));
179
180
// Create a copy of the ZIP instance
181
const zipCopy = zip.clone();
182
183
// Modify the copy without affecting the original
184
zipCopy.file("new-file.txt", "This is only in the copy");
185
zipCopy.remove("readme.txt");
186
187
// Original ZIP is unchanged
188
console.log(zip.files["readme.txt"]); // Still exists
189
console.log(zip.files["new-file.txt"]); // undefined
190
191
// Copy has the modifications
192
console.log(zipCopy.files["readme.txt"]); // undefined (removed)
193
console.log(zipCopy.files["new-file.txt"]); // Exists in copy
194
```
195
196
### Instance Properties
197
198
Access the internal file structure and metadata of the ZIP archive.
199
200
```javascript { .api }
201
/**
202
* Collection of all files and folders in the ZIP
203
* Key is the full path, value is the JSZipObject
204
*/
205
files: {[key: string]: JSZipObject};
206
207
/**
208
* Global comment for the ZIP file
209
*/
210
comment: string | null;
211
212
/**
213
* Current working directory path within the ZIP
214
*/
215
root: string;
216
```
217
218
**Usage Examples:**
219
220
```javascript
221
const zip = new JSZip();
222
223
// Add files and folders
224
zip.file("readme.txt", "Hello");
225
zip.folder("docs").file("guide.md", "# Guide");
226
227
// Access all files directly
228
console.log(Object.keys(zip.files)); // ["readme.txt", "docs/", "docs/guide.md"]
229
230
// Access specific file object
231
const readmeFile = zip.files["readme.txt"];
232
console.log(readmeFile.name); // "readme.txt"
233
console.log(readmeFile.dir); // false
234
235
// Set global ZIP comment
236
zip.comment = "Archive created with JSZip";
237
238
// Check current root (useful when working with folder instances)
239
const docsFolder = zip.folder("docs");
240
console.log(docsFolder.root); // "docs/"
241
```
242
243
## File Options
244
245
Configure file behavior when adding files to the ZIP archive.
246
247
```javascript { .api }
248
interface JSZipFileOptions {
249
/** Set to true if data is base64 encoded */
250
base64?: boolean;
251
/** Set to true for binary data, false for text */
252
binary?: boolean;
253
/** Last modification date */
254
date?: Date;
255
/** Compression method */
256
compression?: Compression;
257
/** Compression options for DEFLATE */
258
compressionOptions?: CompressionOptions | null;
259
/** File comment */
260
comment?: string;
261
/** Set to true for optimized binary strings */
262
optimizedBinaryString?: boolean;
263
/** Create intermediate folders automatically */
264
createFolders?: boolean;
265
/** Set to true to create a directory entry */
266
dir?: boolean;
267
/** DOS file permissions */
268
dosPermissions?: number | null;
269
/** UNIX file permissions */
270
unixPermissions?: number | string | null;
271
}
272
```
273
274
**Usage Examples:**
275
276
```javascript
277
// Add text file with specific date
278
zip.file("changelog.txt", changelogText, {
279
date: new Date("2023-12-01"),
280
comment: "Version 1.0 changes"
281
});
282
283
// Add binary file with compression
284
zip.file("archive.zip", binaryData, {
285
binary: true,
286
compression: "DEFLATE",
287
compressionOptions: { level: 6 }
288
});
289
290
// Add base64 encoded image
291
zip.file("photo.jpg", base64ImageData, {
292
base64: true,
293
createFolders: true // Creates 'photos/' folder if needed
294
});
295
296
// Create directory with permissions
297
zip.file("scripts/", null, {
298
dir: true,
299
unixPermissions: "755"
300
});
301
302
// Add file with UNIX permissions
303
zip.file("run.sh", scriptContent, {
304
unixPermissions: 0o755,
305
comment: "Executable script"
306
});
307
```