nodejs实现文件/目录的压缩和解压
在nodejs里实现文件/目录压缩和解压可以通过 compressing 库来实现,compressing 库目前支持多种压缩格式:tar、gzip、tgz、zip。
安装
npm install compressing
使用的时候需要导入
const compressing = require('compressing');
压缩/解压文件
压缩单个文件
compressing.zip.compressFile('/Users/fkong/test/compressing-demo/package.json', '/Users/fkong/test/package.json.zip')
.then(() => {
console.log('success');
})
.catch(err => {
console.log(err);
});
如果要压缩多个文件,可以使用stream的方式,如下:
const zipStream = new compressing.zip.Stream();
zipStream.addEntry('/Users/fkong/test/compressing-demo/package.json');
zipStream.addEntry('/Users/fkong/test/compressing-demo/package-lock.json');
const destStream = fs.createWriteStream('/Users/fkong/test/destination.zip');
zipStream.pipe(destStream)
.on('finish', () => {
console.log('success');
})
.on('error', () => {
console.log('failure');
});
解压文件到指定目录
compressing.zip.uncompress('/Users/fkong/test/package.json.zip', '/tmp')
.then(() => {
console.log('success');
})
.catch(err => {
console.log(err);
});
压缩/解压目录
压缩一个目录
compressing.zip.compressDir('/Users/fkong/test/compressing-demo', '/Users/fkong/test/compressing-demo.zip')
.then(() => {
console.log('success');
})
.catch(err => {
console.log(err);
});
解压文件到指定目录
compressing.zip.uncompress('/Users/fkong/test/compressing-demo.zip', '/tmp')
.then(() => {
console.log('success');
})
.catch(err => {
console.log(err);
});