Created
May 4, 2018 23:05
-
-
Save senthilmpro/b9d86ea115c075021806b7169028f6f6 to your computer and use it in GitHub Desktop.
Axios async download 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
// 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