Last active
August 2, 2024 13:33
-
-
Save senthilmpro/072f5e69bdef4baffc8442c7e696f4eb to your computer and use it in GitHub Desktop.
Download File using axios : Node.js program
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
'use strict' | |
const Fs = require('fs') | |
const Path = require('path') | |
const Axios = require('axios') | |
async function downloadImage () { | |
const url = 'https://unsplash.com/photos/AaEQmoufHLk/download?force=true' | |
const path = Path.resolve(__dirname, 'images', 'code1.jpg') | |
// axios image download with response type "stream" | |
const response = await Axios({ | |
method: 'GET', | |
url: url, | |
responseType: 'stream' | |
}) | |
// pipe the result stream into a file on disc | |
response.data.pipe(Fs.createWriteStream(path)) | |
// return a promise and resolve when download finishes | |
return new Promise((resolve, reject) => { | |
response.data.on('end', () => { | |
resolve() | |
}) | |
response.data.on('error', () => { | |
reject() | |
}) | |
}) | |
} | |
async function Main(){ | |
const data = await downloadImage(); | |
console.log("DATA ", data); | |
} | |
Main(); |
@leite08 Thank you for correcting me! This was a while ago so i don't know the reason for saying what i did there. I must have had a reason... Don't know what though.
A couple fun notes though :)
- You are assuming default autoClose = true behavior on the write object. This default has changed over time (click history for that function) so i'd prefer to go with an explicit route in this case.
- You always open a file, even if there would be an error on axios. I'm not sure what happens to that file in this case, i'm guessing just an empty file. I'd put the
writer
object below the response. That way you'd at least know the file is opened on a successful http response. It can still fail but that's much less of an edge case then you have now. - You're cheating 😄 The createWriteStream you use is the callback API, i explicitly tried to use the promises API (this function)
Care to go for a second try with the promises api instead? I'm just really curious what you come up with!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@markg85 This is incorrect:
The
finally
block always gets called. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#finallystatements for reference.Maybe you were not "awaiting" inside the try and when the
finally
got executed the state of your code was unexpected?Also, no need to create a Promise at the end of the try. And, since the catch is not doing anything else than jus rethrowing the error, that can be removed too.
The simplified version: