node js file dowload progress bar

Solutions on MaxInterview for node js file dowload progress bar by the best coders in the world

showing results for - "node js file dowload progress bar"
Marlene
02 Jan 2019
1function download(url, callback, encoding){
2        var request = http.get(url, function(response) {
3            if (encoding){
4                response.setEncoding(encoding);
5            }
6            var len = parseInt(response.headers['content-length'], 10);
7            var body = "";
8            var cur = 0;
9            var obj = document.getElementById('js-progress');
10            var total = len / 1048576; //1048576 - bytes in  1Megabyte
11
12            response.on("data", function(chunk) {
13                body += chunk;
14                cur += chunk.length;
15                obj.innerHTML = "Downloading " + (100.0 * cur / len).toFixed(2) + "% " + (cur / 1048576).toFixed(2) + " mb\r" + ".<br/> Total size: " + total.toFixed(2) + " mb";
16            });
17
18            response.on("end", function() {
19                callback(body);
20                obj.innerHTML = "Downloading complete";
21            });
22
23            request.on("error", function(e){
24                console.log("Error: " + e.message);
25            });
26
27        });
28    };
29