node.js如何实现下载⽂件(含下载进度),打开⽂件,删除⽂件或者⽂件夹
1 ⾸先从服务器抓取下载地址和⽂件名字,然后开始截取拼接下载地址
<(‘⽂件的服务器地址’, (event, args) => {
var arr=args.split("+");
downloadpath=arr[0];
console.log(downloadpath)
savepath=arr[1];
openName=arr[2];
mainWindow.webContents.downloadURL(downloadpath)
})
2 开始下载⽂件
mainWindow.(‘will-download’, (event, item, webContents) => {
var TotalBytes();//下载总字节
//设置⽂件存放位置,如果⽤户没有设置保存路径,将使⽤默认⽅式来确定保存路径(通常会提⽰保存对话框)
item.setSavePath(Filename())
fs.stat(‘存放本地路径’+openName, function(err, stat){
if(stat&&stat.isFile()) {
console.log(‘⽂件存在’);
shell.openItem(‘存放本地路径’+openName) //如果已经下载则直接调⽤系统命令⾏打开⽂件,有可能会触发防⽕墙(病毒制作⽅式之⼀)
return false
}else{
console.log("⽂件不存在")  //如果未下载或者⼿动清除,或者被360等清除缓存重新开始下载⽂件
<('updated', (event, state) => {
//console.log(`ToTal bytes: ${TotalBytes()}`)
if (state === ‘interrupted’) {
console.log(‘Download is interrupted but can be resumed’)
} else if (state === ‘progressing’) {
if (item.isPaused()) {
console.log(‘Download is paused’)
} else {
var ReceivedBytes();
mainWindow.webContents.send(‘progress’,parseInt(getReceivedBytes*100/total));//统计下载进度
/
/console.log(Received bytes: ${ReceivedBytes()})
}
}
})
<(‘done’, (event, state) => {
if (state === ‘completed’) {
console.log(‘Download successfully’)
mainWindow.webContents.send(‘status’,‘Download successfully’);
shell.openItem(‘c:\electronMeeting\src\main\resource\’+openName)
//回显 调⽤渲染进程⽅法
mainWindow.webContents.send(‘downstate’,state)
html如何下载
} else {
console.log(Download failed: ${state})
//回显 调⽤渲染进程⽅法
mainWindow.webContents.send(‘downstate’,state)
}
})
}
});
})
3下载完如何清除本地缓存
function deleteFiled(path){
let files = [];
istsSync(path)){
files = fs.readdirSync(path);
files.forEach((file, index) => {
let curPath = path + “/” + file;
if(fs.statSync(curPath).isDirectory()){
delDir(curPath); //递归删除⽂件夹
} else {
fs.unlinkSync(curPath); //删除⽂件
}
});
}
}
传⼊⽂件地址,递归删除⽂件夹即可,如果只删除其中⼀个,改变下删除具体⽂件即可。如有疑问,可在下⾯留⾔。。。。。。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。