zip the folder using built-in modules

感情迁移 提交于 2019-12-14 02:00:42

问题


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:


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);
};


来源:https://stackoverflow.com/questions/38298466/zip-the-folder-using-built-in-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!