Created
July 21, 2021 20:07
-
-
Save senthilmpro/84991a36c8c11bf68a6a7f37dbbc2319 to your computer and use it in GitHub Desktop.
axios download progress in nodeJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { default: axios } = require("axios"); | |
const fs = require("fs"); | |
const downloadFile = async (url, filename) => { | |
const { data, headers, request } = await axios({ | |
url: url, | |
method: "GET", | |
responseType: "stream", | |
}); | |
//content length in bytes | |
const contentLength = headers["content-length"]; | |
let name = filename || url.split("/").pop(); | |
let chunkSize = 0; | |
const sizeInMB = (size) => (size / (1024 * 1024)).toFixed(2); | |
const percent = (num, den) => Math.floor((num * 100) / den); | |
data.on("data", (chunk) => { | |
chunkSize += chunk.length; | |
console.log( | |
`Completed ${sizeInMB(chunkSize)} MB of ${sizeInMB( | |
contentLength | |
)} MB : ${percent(chunkSize, contentLength)}%` | |
); | |
}); | |
data.pipe(fs.createWriteStream(name)); | |
return new Promise((res) => { | |
data.on("end", () => { | |
res(data); | |
}); | |
}); | |
}; | |
module.exports = { | |
downloadFile, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment