Last active
April 27, 2024 05:26
-
-
Save senthilmpro/04ea6c086bcb592beb8083214a630548 to your computer and use it in GitHub Desktop.
Download files using Axios.js
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
/** | |
* Download files and save it to disk using axios.js | |
* Download images, zip files using this function | |
* | |
* @param {Request URL} reqUrl | |
* @param {File name} fileName | |
*/ | |
function downloadFile(reqUrl, fileName){ | |
axios({ | |
method: "GET", | |
url: reqUrl, | |
responseType: "stream" | |
}).then(res => { | |
if (res.status == 200) { | |
const path = require("path"); | |
const SUB_FOLDER = SUB_FOLDER || ""; | |
fileName = fileName || reqUrl.split("/").pop(); | |
const dir = path.resolve(__dirname, SUB_FOLDER, fileName); | |
res.data.pipe(fs.createWriteStream(dir)); | |
res.data.on("end", () => { | |
console.log("download completed"); | |
}); | |
} else { | |
console.log(`ERROR >> ${res.status}`); | |
} | |
}).catch(err => { | |
console.log("Error ",err); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you recently came in handy