zip the folder using built-in modules

2019-07-15 06:44发布

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 and other built-in modules?

I'm looking for a way to do it without external dependencies.

The other option is to run local processes on mac, windows etc. for zip, tar etc., I'm sure there are command line utilities on either of the operating system

This is not an answer but it's somehow related to what I'm looking for, it's spawning a local process to zip.

Another link I'm looking at.

Unix command for zip | exec and spawn

The commands I tried on terminal which worked,

  1. /usr/bin/zip test.zip /resources/html/article
  2. du -hs test.zip

Code

var zip = function(path) {
    const spawn = require('child_process').spawn;
    const exec = require('child_process').exec;
    exec("which zip", function (error, stdout, stderr) {
        if (error) {
            console.log(error);
        } else {
            exec(stdout + " -r " + path + "/test.zip " + path, function(error, stdout, stderr){
                if(error) {
                    console.log(error);
                } else {
                    exec("du -hs test.zip", function(error, stdout, stderr){
                        console.log('done');
                        console.log(arguments);
                    });
                }
            })
        }
    });
};

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-15 07:07

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.

function execute(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){
            return execute(zip  + " -r abc.zip " + path);
        })
        .then(function(result){
            return execute("du -hs abc.zip");
        })
        .then(function(result){
            console.log(result);
        })
        .catch(console.error);
};
查看更多
登录 后发表回答