node.js压缩和解压缩

时间:2020-12-04 05:14:36

推荐一个极其简单、及其好用的node.js的压缩和解压缩类库  compressing

支持格式: tar、gzip、tgz、zip

以zip为例,tar,tgz和gzip与zip相同。

压缩文件:

const compressing = require('compressing');
compressing.zip.compressFile('logs/info-2018-06-07.log', 'logs/test.zip').then(() => {}).catch(() => {});

//或者
await compressing.zip.compressFile('logs/info-2018-06-07.log', 'logs/test.zip')

压缩文件夹:

const compressing = require('compressing');
compressing.zip.compressDir('logs', 'test3.zip').then(()=>{}).catch(()=>{});

//或者
await compressing.zip.compressDir('logs', 'test3.zip')

使用Stream压缩多个文件(非常强大)

const fs=require('fs');
const compressing = require('compressing');
const zipStream = new compressing.zip.Stream();
zipStream.addEntry('./logs/error-2018-06-07.log')
zipStream.addEntry('./logs/info-2018-06-07.log')

const destStream = fs.createWriteStream('test4.zip');

const pipe = require('multipipe');
pipe(zipStream, destStream, (err) => {
    console.log(err);
})

Stream可以是dir、file、buffer、stream

// dir
zipStream.addEntry('dir/path/to/compress');

// file
zipStream.addEntry('file/path/to/compress');

// buffer
zipStream.addEntry(buffer);

// stream
zipStream.addEntry(stream);

解压缩:

const compressing = require('compressing');
compressing.zip.uncompress('test3.zip', 'test3').then(() => {}).catch(() => {});
//或者
await compressing.zip.uncompress('test3.zip', 'test3') //如果要解压到当前目录换成 './'

 

更多内容:

https://github.com/node-modules/compressing

https://www.npmjs.com/package/compressing