Skip to content

Instantly share code, notes, and snippets.

@senthilmpro
Last active April 27, 2024 05:26
Show Gist options
  • Save senthilmpro/04ea6c086bcb592beb8083214a630548 to your computer and use it in GitHub Desktop.
Save senthilmpro/04ea6c086bcb592beb8083214a630548 to your computer and use it in GitHub Desktop.
Download files using Axios.js
/**
* 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);
});
}
@jaysonwu991
Copy link

jaysonwu991 commented Oct 9, 2022

Thanks for this approach, but this line should be const SUB_FOLDER = process.env.SUB_FOLDER || "";, otherwise there should be an Error.

@asowder3943
Copy link

asowder3943 commented Jan 8, 2023

Thank you recently came in handy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment