nodejs中使用archive压缩文件的实现代码
前言
archive是一款在nodejs中可以实现跨平台打包的工具
可以将文件压缩为zip或rar格式
是一个比较好用的第三方模块
install
npminstallarchiver--save
archivegithub地址:https://github.com/archiverjs/node-archiver
QuickStart
//requiremodules
varfs=require('fs');
vararchiver=require('archiver');
//createafiletostreamarchivedatato.
varoutput=fs.createWriteStream(__dirname+'/example.zip');
//设置压缩格式为zip
vararchive=archiver('zip',{
zlib:{level:9}//Setsthecompressionlevel.
});
//listenforallarchivedatatobewritten
//'close'eventisfiredonlywhenafiledescriptorisinvolved
output.on('close',function(){
console.log(archive.pointer()+'totalbytes');
console.log('archiverhasbeenfinalizedandtheoutputfiledescriptorhasclosed.');
});
//Thiseventisfiredwhenthedatasourceisdrainednomatterwhatwasthedatasource.
//ItisnotpartofthislibrarybutratherfromtheNodeJSStreamAPI.
//@see:https://nodejs.org/api/stream.html#stream_event_end
output.on('end',function(){
console.log('Datahasbeendrained');
});
//goodpracticetocatchthiserrorexplicitly
archive.on('error',function(err){
throwerr;
});
//pipearchivedatatothefile
archive.pipe(output);
//appendafilefromstream
varfile1=__dirname+'/file1.txt';
archive.append(fs.createReadStream(file1),{name:'file1.txt'});
//appendafilefromstring
archive.append('stringcheese!',{name:'file2.txt'});
//appendafilefrombuffer
varbuffer3=Buffer.from('buffit!');
archive.append(buffer3,{name:'file3.txt'});
//appendafile
archive.file('file1.txt',{name:'file4.txt'});
//appendfilesfromasub-directoryandnamingit`new-subdir`withinthearchive
archive.directory('subdir/','new-subdir');
//appendfilesfromasub-directory,puttingitscontentsattherootofarchive
archive.directory('subdir/',false);
//appendfilesfromaglobpattern
archive.glob('subdir/*.txt');
//finalizethearchive(iewearedoneappendingfilesbutstreamshavetofinishyet)
//'close','end'or'finish'maybefiredrightaftercallingthismethodsoregistertothembeforehand
archive.finalize();
实际使用
实际使用中情况可能会比较多
需要打包的源文件一般为远程文件,比如某一个第三方的文件存放地址,这时则需要先将第三方文件下载到本地
示例方法,可以根据实际需要修改相应的参数
functiondownload(files){
//下载文件的本地存档地址
//示例files=[{name:'xxxx.js',url:'https://xx/xx/xxxx.js'}]
letdirPath=path.resolve(__dirname,'文件存放的本地位置')
mkdir(dirPath);
lettmps=files.map((item,index)=>{
letstream=fs.createWriteStream(path.resolve(dirPath,item.name));
returnnewPromise((resolve,reject)=>{
try{
request(item.url).pipe(stream).on("close",function(err){
console.log("文件["+item.name+"]下载完毕");
resolve({
url:path.resolve(dirPath,item.name),
name:item.name
})
});
}catch(e){
reject(e||'')
}
})
});
returnnewPromise((res,rej)=>{
Promise.all(tmps).then((result)=>{
console.log(result)
res(result)
}).catch((error)=>{
console.log(error||'')
})
})
}
//创建文件夹目录
functionmkdir(dirPath){
if(!fs.existsSync(dirPath)){
fs.mkdirSync(dirPath);
console.log("文件夹创建成功");
}else{
console.log("文件夹已存在");
}
}
将下载到本地的文件打包为一个zip文件,可以参照QuickStart中的api组合使用
//appendfilesfromasub-directory,puttingitscontentsattherootofarchive
archive.directory('subdir/',false);
//要注意第二个参数false,这个参数代表打包后的文件相对于output的目录结构,不写这个参数代表按照第一个参数('subdir/')的目录层级
打包之后的文件位置是在本地位置,此时在推送到前端页面中下载url需要组装成http或https的地址
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。