Skip to content

How to download an image from URL in Node

New Course Coming Soon:

Get Really Good at Git

import os from 'os'
import fs from 'fs'
import https from 'https'

async function downloadFileFromURL(url, fileLocation) {
  return await new Promise((resolve, reject) => {
    https
      .get(url, (response) => {
        const code = response.statusCode ?? 0

        if (code >= 400) {
          return reject(new Error(response.statusMessage))
        }

        // handle redirects
        if (code > 300 && code < 400 && !!response.headers.location) {
          return await downloadFile(response.headers.location)
        }

        // save the file to disk
        const fileWriter = fs
          .createWriteStream(fileLocation)
          .on('finish', () => {
            resolve({
              fileLocation,
              contentType: response.headers['content-type'],
            })
          })

        response.pipe(fileWriter)
      })
      .on('error', (error) => {
        reject(error)
      })
  })
}

const imageUrl = 'https://.... bla bla'
const fileLocation = os.tmpdir() + '/' + rnd(10, rnd.alphaLower)

await downloadFileFromURL(imageUrl, fileLocation)
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my Node.js Handbook
→ Read my Node.js Tutorial on The Valley of Code

Here is how can I help you: