Archiving a file/folder using nodejs is very simple. I have used nodejs archiver library to zip directory and fs library to get the file information in this post.
const fs = require('fs');
var archiver = require('archiver');
function zip_directory(filename, copyFrom, copyToPath){
var copyTo = copyToPath + filename;
if(!fs.existsSync(copyToPath)){
fs.mkdirSync(copyToPath);
}
var output = fs.createWriteStream(copyTo);
var archive = archiver('zip', {
zlib: { level: 9 } // Sets the compression level.
});
output.on('close', function () {
console.log(`\n<< ARCHIVE LOG: TOTAL BYTES ${archive.pointer()} >>`);
console.log(`\n<< ARCHIVE LOG: archiver has been finalized and the output file descriptor has closed. >>`);
});
output.on('end', function() {
console.log(`\n<< ARCHIVE LOG: END : Data has been drained. >>`);
});
archive.on('warning', function(err) {
if (err.code === 'ENOENT') {
console.log(`\n<< ARCHIVE LOG: ENOENT ${err} >>`);
} else {
console.log(`\n<< ARCHIVE LOG: WARNING ${err} >>`);
}
});
archive.on('error', function(err){
console.log(`\n<< ARCHIVE LOG: Error : ${err} >>`);
});
try {
archive.pipe(output);
archive.directory(copyFrom, { name: filename });
archive.finalize();
} catch (err) {
console.log(`\n<< ARCHIVE LOG: Error : ${err} >>`);
}
}
zip_directory('myzipfile.zip', '/home/', '/opt/zipfiles/');
Note: Should install required packages as well as declare require things in code.
