Skip to content Skip to sidebar Skip to footer

Zip The Folder Using Built-in Modules

Edit -> Can someone suggest edits to my answer, for instance I'm not sure if exec is better or spawn? Is it possible to zip the directory/folder with it's contents using zlib a

Solution 1:

Tested on mac and works. Can someone test this on Linux? Any ideas for windows?

Notice the use of stdout.trim() to get rid of an extra \n character returned from console.

functionexecute(command) {
    const exec = require('child_process').exec;
    return new Promise(function(resolve, reject){
        exec(command, function(error, stdout, stderr){
            if(error) {
                reject(error);
            } else {
                stderr ? reject(stderr) : resolve(stdout.trim());
            }
        });
    });
}

Function zip

var zip = function(path) {
    execute("which zip")
        .then(function(zip){
            returnexecute(zip  + " -r abc.zip " + path);
        })
        .then(function(result){
            returnexecute("du -hs abc.zip");
        })
        .then(function(result){
            console.log(result);
        })
        .catch(console.error);
};

Solution 2:

**The simplest and popular method is - child_process exec to execute commands **

const exec = require('child_process').exec;

const ls = exec(`tar -czvf filename.tar.gz dirPathToZip && mv fileName.tar.gz  moveZipFileToPath`);

ls.stdout.on('data', (data) => {
   console.log(`stdout: ${data}`)
});

ls.stderr.on('data', (data) => {
   console.error(`stderr: ${data}`)
});

ls.on('close', (code) => {
   fs.rmdirSync(pathDoDeleteDir, { recursive: true })
})

Post a Comment for "Zip The Folder Using Built-in Modules"