Skip to content

Commit 81d09ca

Browse files
authored
Merge pull request #266 from Dewep/master
Add async version of addLocalFile
2 parents f66dc60 + 237bb7f commit 81d09ca

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

Diff for: adm-zip.js

+78
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,84 @@ 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+
p = p.normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^\x20-\x7E]/g, '') // accent fix
340+
if (filter(p)) {
341+
if (p.charAt(p.length - 1) !== "/") {
342+
fs.readFile(items[i], function (err, data) {
343+
if (err) {
344+
callback(undefined, err);
345+
} else {
346+
self.addFile(zipPath + p, data, '', 0);
347+
next();
348+
}
349+
})
350+
} else {
351+
self.addFile(zipPath + p, Buffer.alloc(0), "", 0);
352+
next();
353+
}
354+
} else {
355+
next();
356+
}
357+
358+
} else {
359+
callback(true, undefined);
360+
}
361+
}
362+
363+
next();
364+
}
365+
});
366+
},
367+
290368
/**
291369
* Allows you to create a entry (file or directory) in the zip file.
292370
* If you want to create a directory the entryName must end in / and a null buffer should be provided.

0 commit comments

Comments
 (0)