I want to create a zip archive and unzip it in node.js.
I can\'t find any node implementation.
I've found it easiest to roll my own wrapper around 7-zip, but you could just as easily use zip or whatever command line zip tool is available in your runtime environment. This particular module just does one thing: zip a directory.
const { spawn } = require('child_process');
const path = require('path');
module.exports = (directory, zipfile, log) => {
return new Promise((resolve, reject) => {
if (!log) log = console;
try {
const zipArgs = ['a', zipfile, path.join(directory, '*')];
log.info('zip args', zipArgs);
const zipProcess = spawn('7z', zipArgs);
zipProcess.stdout.on('data', message => {
// received a message sent from the 7z process
log.info(message.toString());
});
// end the input stream and allow the process to exit
zipProcess.on('error', (err) => {
log.error('err contains: ' + err);
throw err;
});
zipProcess.on('close', (code) => {
log.info('The 7z exit code was: ' + code);
if (code != 0) throw '7zip exited with an error'; // throw and let the handler below log it
else {
log.info('7zip complete');
return resolve();
}
});
}
catch(err) {
return reject(err);
}
});
}
Use it like this, assuming you've saved the above code into zipdir.js. The third log param is optional. Use it if you have a custom logger. Or delete my obnoxious log statements entirely.
const zipdir = require('./zipdir');
(async () => {
await zipdir('/path/to/my/directory', '/path/to/file.zip');
})();