Skip to content

Commit 20c9cb8

Browse files
committed
Add async version of addLocalFile
Use open and readFile instead of existsSync and readFileSync. There are still some sync functions left in the Utils.findFiles call, but the impact is minimal compared to the readFileSync.
1 parent cb300c9 commit 20c9cb8

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

adm-zip.js

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,83 @@ module.exports = function (/*String*/input) {
287287
}
288288
},
289289

290+
/**
291+
* Asynchronous addLocalFile
292+
* @param localPath
293+
* @param callback
294+
* @param zipPath optional path inside zip
295+
* @param filter optional RegExp or Function if files match will
296+
* be included.
297+
*/
298+
addLocalFolderAsync: function (/*String*/localPath, /*Function*/callback, /*String*/zipPath, /*RegExp|Function*/filter) {
299+
if (filter === undefined) {
300+
filter = function () {
301+
return true;
302+
};
303+
} else if (filter instanceof RegExp) {
304+
filter = function (filter) {
305+
return function (filename) {
306+
return filter.test(filename);
307+
}
308+
}(filter);
309+
}
310+
311+
if (zipPath) {
312+
zipPath = zipPath.split("\\").join("/");
313+
if (zipPath.charAt(zipPath.length - 1) !== "/") {
314+
zipPath += "/";
315+
}
316+
} else {
317+
zipPath = "";
318+
}
319+
// normalize the path first
320+
localPath = pth.normalize(localPath);
321+
localPath = localPath.split("\\").join("/"); //windows fix
322+
if (localPath.charAt(localPath.length - 1) !== "/")
323+
localPath += "/";
324+
325+
var self = this;
326+
fs.open(localPath, 'r', function (err, fd) {
327+
if (err && err.code === 'ENOENT') {
328+
callback(undefined, Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath));
329+
} else if (err) {
330+
callback(undefined, err);
331+
} else {
332+
var items = Utils.findFiles(localPath);
333+
var i = -1;
334+
335+
var next = function () {
336+
i += 1;
337+
if (i < items.length) {
338+
var p = items[i].split("\\").join("/").replace(new RegExp(localPath.replace(/(\(|\))/g, '\\$1'), 'i'), ""); //windows fix
339+
if (filter(p)) {
340+
if (p.charAt(p.length - 1) !== "/") {
341+
fs.readFile(items[i], function (err, data) {
342+
if (err) {
343+
callback(undefined, err);
344+
} else {
345+
self.addFile(zipPath + p, data, '', 0);
346+
next();
347+
}
348+
})
349+
} else {
350+
self.addFile(zipPath + p, Buffer.alloc(0), "", 0);
351+
next();
352+
}
353+
} else {
354+
next();
355+
}
356+
357+
} else {
358+
callback(true, undefined);
359+
}
360+
}
361+
362+
next();
363+
}
364+
});
365+
},
366+
290367
/**
291368
* Allows you to create a entry (file or directory) in the zip file.
292369
* If you want to create a directory the entryName must end in / and a null buffer should be provided.

0 commit comments

Comments
 (0)