30
loading...
This website collects cookies to deliver better user experience
.zip
file whenever it is found.async function extractZip(source, target) {
try {
await extract(source, { dir: target });
console.log("Extraction complete");
} catch (err) {
console.log("Oops: extractZip failed", err);
}
}
const unzipFiles = async function (dirPath) {
const files = fs.readdirSync(dirPath);
await Promise.all(
files.map(async (file) => {
if (fs.statSync(dirPath + "/" + file).isDirectory()) {
await unzipFiles(dirPath + "/" + file);
} else {
const fullFilePath = path.join(dirPath, "/", file);
const folderName = file.replace(".zip", "");
if (file.endsWith(".zip")) {
zippedFiles.push(folderName);
await extractZip(fullFilePath, path.join(dirPath, "/", folderName));
await unzipFiles(path.join(dirPath, "/", folderName));
}
}
})
);
};
dirPath
: file extraction path
The fs.readdirSync()
method is used to synchronously read the contents of a given directory. The method returns an array with all the file names or objects in the directory.
Now, the main challenge was to loop through all the folders/files asynchronously. We cannot use forEach
since it doesn't support async/await
keyword. Traditional for loop syntax works with await
keyword. But I wanted to use the more common array method map()
.
If you use await
with map()
it returns array of promises. Hence, to resolve all promises await Promise.all(arrayOfPromises)
is used here.
For more details on async/await
in loops refer to this wonderful article
if (fs.statSync(dirPath + "/" + file).isDirectory()) {
await unzipFiles(dirPath + "/" + file);
}
isDirectory()
method is used. If its a folder then call same method again i.e unzipFiles()
else {
const fullFilePath = path.join(dirPath, "/", file);
const folderName = file.replace(".zip", "");
if (file.endsWith(".zip")) {
zippedFiles.push(folderName);
await extractZip(fullFilePath, path.join(dirPath, "/", folderName));
await unzipFiles(path.join(dirPath, "/", folderName));
}
If a file is found then we will call the extractZip()
method with source
and target
with their absolute paths.
If we don't specify the target
, or give it a current path then it will extract all the files in current directory itself. But I wanted to extract the zip to their respective folder names.
To achieve this, I have spliced the folder name from .zip file passed it as a target
to extractZip()
method.
Now there is one more catch in the last line i.e
await unzipFiles(path.join(dirPath, "/", folderName));
unzipFiles()
to traverse through the extracted files.