How to download images using Node.js

How do you download the file?

I asked myself this question when I had to download files from the server programmatically.

I have to connect to the server, download the file, and store it locally.

This is the code I used:

const fs = require('fs')
const request = require('request')

const download = (url, path, callback) => { request.head(url, (err, res, body) => { request(url) .pipe(fs.createWriteStream(path)) .on(‘close’, callback) }) }

const url = ‘https://…’ const path = ‘./images/image.png’

download(url, path, () => { console.log(‘✅ Done!’) })

The code usesfsBuilt-in modules andrequestModule.

requestMust install:

npm install request

Note that the request module was recently deprecated, which means it’s “complete” and no new changes will be applied to it. Only fixes. It doesn’t mean it will stop working and it does not mean we should stop using it.

Download my free Node.js Handbook


More node tutorials: