使用内置模块压缩文件夹

zip the folder using built-in modules

Edit -> 有人可以建议编辑我的答案,例如我不确定 exec 更好还是 spawn?


是否可以使用 zlib 和其他内置模块压缩 directory/folder 及其内容?

我正在寻找一种无需外部依赖的方法。

另一个选项是 运行 mac、windows 等上的本地进程,用于 zip、tar 等,我确定有命令行任一操作系统上的实用程序

This is not an answer 但它与我正在寻找的东西有某种关系,它正在生成一个本地进程来压缩。

另一个 link 我正在看。

Unix command for zip | exec and spawn

我在终端上尝试的命令有效,

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

代码

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

已在 mac 上测试并有效。有人可以在 Linux 上测试吗? windows 有什么想法吗?

注意使用 stdout.trim() 来删除从控制台返回的额外 \n 字符。

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

函数压缩

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

**最简单流行的方法是——child_processexec执行命令**

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