for (var i=0;i<dataArray.length;i++) { var timenow=Date.now();//调用的时候,打个时间戳 const options = { directory: downloadPath, filename: dataArray[i].title + '.' + dataArray[i].fileType, saveAs: false, extension: dataArray[i].fileType, openFolderWhenDone: false, showProgressBar: true, showBadge: true, }; var downloader = new Downloader(dataArray[i], options); downloader.data.timeid=timenow;//存储唯一标识 downloader.start(); downloader.onStart = () => { // 下载开始 handleDownload.push(downloader); mainWindow.webContents.send('consolelog2', '检查代码在此执行次数'); }; downloader.onTotalProgress = (progress) => { // 更新下载进度 downloadArray.set(downloader.data.timeid, { title: downloader.data.title, sUrl: downloader.data.sUrl, progress: downloader.data.progress, size: downloader.data.size, status:downloader.data.status, timeid:downloader.data.timeid }); mainWindow.webContents.send('consolelog', downloadArray); mainWindow.webContents.send('donwloadStatus', true); }; downloader.onCompleted = () => { if(downloader.data.progress==100&&downloader.data.status=='process'){ mainWindow.webContents.send('endDownload', JSON.stringify(downloader)); mainWindow.webContents.send('donwloadStatus', false); downloader.data.status='complete' } if(downloader.data.progress<100){ mainWindow.webContents.send('donwloadStatus', true); } mainWindow.webContents.send('consolelog', downloadArray); }; } return JSON.stringify(dataArray); // 返回值将作为 Promise 的 resolved 值 }); 这段代码中,如果我是多个下载器,var downloader = new Downloader(dataArray[i], options); 这里就会导致重复创建一个名字的下载,导致我操作 downloader.start(); 的时候,会触发多个下载器的 start ,我要怎么优化。把下载器分离出独立
时间: 2024-02-06 18:03:12 浏览: 80
可以将 Downloader 类提取出来,单独作为一个模块,然后在循环中实例化多个 Downloader 对象,这样就可以避免重复创建相同名字的下载器。示例代码如下:
1. 创建 Downloader 类的模块 downloader.js:
```javascript
const request = require('request');
const fs = require('fs');
const path = require('path');
class Downloader {
constructor(data, options) {
this.data = data;
this.options = options;
this.req = null; // request 对象
this.writeStream = null; // 文件写入流
}
start() {
const { sUrl } = this.data;
const { directory, filename, saveAs, extension } = this.options;
const filePath = path.join(directory, saveAs ? filename : `${Date.now()}.${extension}`);
this.writeStream = fs.createWriteStream(filePath);
this.req = request
.get(sUrl)
.on('error', (err) => {
console.error(`请求 ${sUrl} 出错:${err.message}`);
this.data.status = 'failed';
})
.on('response', (response) => {
if (response.statusCode === 200) {
this.data.size = parseInt(response.headers['content-length'], 10);
} else {
this.data.status = 'failed';
}
})
.on('data', (chunk) => {
this.writeStream.write(chunk);
this.data.progress = (this.writeStream.bytesWritten / this.data.size) * 100;
})
.on('end', () => {
this.writeStream.end();
this.data.progress = 100;
this.data.status = 'complete';
});
}
pause() {
if (this.req) {
this.req.pause();
}
if (this.writeStream) {
this.writeStream.close();
}
}
resume() {
this.start();
}
cancel() {
this.pause();
const { directory, saveAs, extension } = this.options;
const filePath = path.join(directory, saveAs ? this.data.filename : `${Date.now()}.${extension}`);
fs.unlink(filePath, (err) => {
if (err) {
console.error(`删除文件 ${filePath} 出错:${err.message}`);
}
});
}
}
module.exports = Downloader;
```
2. 修改原来的代码,引入 downloader.js 模块,并实例化多个 Downloader 对象:
```javascript
const Downloader = require('./downloader');
...
for (let i = 0; i < dataArray.length; i++) {
const timenow = Date.now();
const options = {
directory: downloadPath,
filename: dataArray[i].title + '.' + dataArray[i].fileType,
saveAs: false,
extension: dataArray[i].fileType,
openFolderWhenDone: false,
showProgressBar: true,
showBadge: true,
};
const downloader = new Downloader(dataArray[i], options);
downloader.data.timeid = timenow;
downloader.start();
handleDownload.push(downloader);
downloader.onTotalProgress = (progress) => {
downloadArray.set(downloader.data.timeid, {
title: downloader.data.title,
sUrl: downloader.data.sUrl,
progress: downloader.data.progress,
size: downloader.data.size,
status: downloader.data.status,
timeid: downloader.data.timeid
});
mainWindow.webContents.send('consolelog', downloadArray);
mainWindow.webContents.send('donwloadStatus', true);
};
downloader.onCompleted = () => {
if (downloader.data.progress === 100 && downloader.data.status === 'process') {
mainWindow.webContents.send('endDownload', JSON.stringify(downloader));
mainWindow.webContents.send('donwloadStatus', false);
downloader.data.status = 'complete';
}
if (downloader.data.progress < 100) {
mainWindow.webContents.send('donwloadStatus', true);
}
mainWindow.webContents.send('consolelog', downloadArray);
};
}
```
阅读全文