zip the folder using built-in modules

<strong>Edit</strong> -> Can someone suggest edits to my answer, for instance I'm not sure if exec is better or spawn?

<hr>

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,

<ol> <li>/usr/bin/zip test.zip /resources/html/article</li> <li>du -hs test.zip</li> </ol>

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

Answer1:

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

<strong>Function zip</strong>

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

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:zip the folder using built-in modules