How to download an image from URL in Node
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)
→ Get my Node.js Handbook
→ I wrote 17 books to help you become a better developer:
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025