如果有人想在不使用其他库但只请求的情况下知道进度,那么您可以使用以下方法:
function downloadFile(file_url , targetPath){
// Save variable to know progress
var received_bytes = 0;
var total_bytes = 0;
var req = request({
method: 'GET',
uri: file_url
});
var out = fs.createWriteStream(targetPath);
req.pipe(out);
req.on('response', function ( data ) {
// Change the total bytes value to get progress later.
total_bytes = parseInt(data.headers['content-length' ]);
});
req.on('data', function(chunk) {
// Update the received bytes
received_bytes += chunk.length;
showProgress(received_bytes, total_bytes);
});
req.on('end', function() {
alert("File succesfully downloaded");
});
}
function showProgress(received,total){
var percentage = (received * 100) / total;
console.log(percentage + "% | " + received + " bytes out of " + total + " bytes.");
// 50% | 50000 bytes received out of 100000 bytes.
}
downloadFile("https://static.pexels.com/photos/36487/above-adventure-aerial-air.jpg","c:/path/to/local-image.jpg");
该received_bytes
变量保存每个发送的块长度的总和,并根据total_bytes
检索进度。