- Published on
How to zip and unzip Directory in Node.js
- Authors
- Name
- Ashik Nesin
- @AshikNesin
Sometimes when working with files, we might want to quickly zip and unzip a directory on the fly using Node.js
For such cases, AdmZip is a good choice.
With that package, we can perform a lot of operations pretty easily like zipping, unzipping, reading its contents, and adding files to an existing zip.
In this blog post, let's see how to create a new zip file and also extract a zip's content, all within Node.js.
Dependency
npm install adm-zip
import AdmZip from 'adm-zip';
const zipDirectory = async (sourceDir, outputFilePath) => {
const zip = new AdmZip();
zip.addLocalFolder(sourceDir);
await zip.writeZipPromise(outputFilePath);
console.log(`Zip file created: ${outputFilePath}`);
};
const unzipDirectory = async (inputFilePath, outputDirectory) => {
const zip = new AdmZip(inputFilePath);
return new Promise((resolve, reject) => {
zip.extractAllToAsync(outputDirectory, true, (error) => {
if (error) {
console.log(error);
reject(error);
} else {
console.log(`Extracted to "${outputDirectory}" successfully`);
resolve();
}
});
});
};
await zipDirectory('/path/to/sourceDir', `/path/to/outputFilePath.zip`)
await unzipDirectory('/path/to/inputFilePath.zip', `/path/to/outputDirectory`)
Happy zipping unzipping!