Reputation: 1695
Here is my function to get number of files within a ZIP package.
// check if .ZIP package contains at least one HTML file and return number of files
function validateArchive(path, callback) {
var filesCount = 0;
var unzipParser = unzip.Parse();
var readStream = fs.createReadStream(path).pipe(unzipParser);
unzipParser.on('error', function(err) {
throw err;
});
readStream.on('entry', function (entry) {
var fileName = entry.path;
var type = entry.type; // 'Directory' or 'File'
if (type == 'File') {
var fext = fileName.split('.')[1];
if (fext === 'html') {
filesCount++;
}
}
entry.autodrain();
});
// returns number of files
setTimeout(function () {
callback(filesCount);
}, 1000);
}
As you can see I have a problem with returning number of files because asynchronous process in place.
Any ideas hot to return number of files without using setTimeout
method?
Upvotes: 1
Views: 1063
Reputation: 36777
You can listen to the close
event:
unzipParser.on('close', function() {
callback(filesCount);
});
which is emitted when the end of zip is reached.
Upvotes: 5