0
如果我使用helperFile
,我只能通過返回Promise將download complete
發送回組件。但是如何將進度變量發送回組件以稍後使用它來實現下載進度欄。通過Promise發送下載進度
我也能夠做到這一點,如果我把所有的代碼放在組件內,但那太可怕了。
助手文件
const request = require('request');
class helperFile{
static downloadFile(file_url, targetPath, callback) {
return new Promise(function (resolve, reject) {
let received_bytes = 0;
let total_bytes = 0;
let req = request({
method: 'GET',
uri: file_url
});
let out = fs.createWriteStream(targetPath);
req.pipe(out);
req.on('response', function (data) {
total_bytes = parseInt(data.headers['content-length']);
});
req.on('data', function (chunk) {
received_bytes += chunk.length;
let progress = (received_bytes * 100)/total_bytes;
return progress
});
req.on('end', function() {
resolve(true)
console.log("File succesfully downloaded");
});
})
}
}
陣營組件
import helperFile from '../actions/download'
handleDownloadFile() {
helperFile.downloadFile('https:...', 'path')
.then((response) => console.log(response))
}
預期的輸出應該是1,2,3,... 100,並完成
true
時。
,因爲我需要使用它的組件來實現下載進度條。 –
@CristianMuscalu答覆已更新 – Erazihel