Published on

How to zip and unzip Directory in Node.js


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.


npm install adm-zip
import AdmZip from 'adm-zip';

const zipDirectory = async (sourceDir, outputFilePath) => {
    const zip = new AdmZip();
    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) {
            } else {
                console.log(`Extracted to "${outputDirectory}" successfully`);

await zipDirectory('/path/to/sourceDir', `/path/to/`)
await unzipDirectory('/path/to/', `/path/to/outputDirectory`)

Happy zipping unzipping!