Skip to content

Instantly share code, notes, and snippets.

@senthilmpro
Created May 4, 2018 23:05
Show Gist options
  • Save senthilmpro/b9d86ea115c075021806b7169028f6f6 to your computer and use it in GitHub Desktop.
Save senthilmpro/b9d86ea115c075021806b7169028f6f6 to your computer and use it in GitHub Desktop.
Axios async download in nodeJS
// async download
const axios = require("axios"),
fs = require("fs"),
path = require("path");
const SUB_FOLDER = "";
const IMG_NAME = "img.jpg";
/**
* this will dl.image
* @param {*} reqUrl
*/
async function dlImage(reqUrl) {
const dir = path.resolve(__dirname, SUB_FOLDER, IMG_NAME);
var resp = await axios({
method: "GET",
url: reqUrl,
responseType: "stream"
});
resp.data.pipe(fs.createWriteStream(dir));
return new Promise((resolve, reject) => {
resp.data.on("end", () => {
console.log("download complete");
resolve();
});
resp.data.on("error", () => {
console.log("ERROR ");
reject();
});
});
}
async function main() {
console.log("ENTERING MAIN FUNCTION");
const reqUrl =
"https://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-644280.jpg";
await dlImage(reqUrl);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment