Last active
April 27, 2024 03:37
-
-
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This got me going - and annoyed - by nodejs.
I wanted to try the
fs
promises version of fs to handle a download. Turns out that it's quite different and even feels c-like.Here's a download function that uses fs promises and axios as http handler:
Frankly, it's ugly. I thought promises were to make things easier and prettier (and they often are!), but the case of downloading a file (specially the writer object that you need to promisify still) just makes it look messy.
Note the use of
finally
to close the file handle. The?
part infile?.close()
handles the error case neatly.Also note that this means you must not return within the try block else the
finally
won't be called.Call with something like:
await downloadFile("https://whatever/url/to/file", "/destination/file"
);