DEV Community

Cover image for Saving Image from URL using Node.js
Dimitrij Agal
Dimitrij Agal

Posted on

Saving Image from URL using Node.js

I have been creating a scraper and need an automation to download some images. I spend hours to finally get it right. So, here I am writing this post, hoping that it would help someone in needs (or even future me finds this from search engine).

There may be a lot of other way, but here's the one that works for me today.

const fs = require('fs');
const fetch = require('node-fetch');

const url = "https://www.something.com/.../image.jpg"

async function download() {
  const response = await fetch(url);
  const buffer = await response.buffer();
  fs.writeFile(`./image.jpg`, buffer, () => 
    console.log('finished downloading!'));
}

Enter fullscreen mode Exit fullscreen mode

Please note that fs is included in the node framework, while node-fetch may need to be installed first.

You can combine this with any scraper library like puppeteer.

Latest comments (5)

Collapse
 
stefanzero profile image
Stefan Musarra

With Node version 18, there is a native fetch method. However, the response object returned does not have a .buffer method. If you use the native fetch, this minor modification is required:

async function download(url, outputFile) {
    const response = await fetch(url);
    const arrayBuffer = await response.arrayBuffer();
    const buffer = Buffer.from(arrayBuffer, 'binary');
    fs.writeFileSync('image.jpg', buffer);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rascode profile image
Justin Rascoe

Straight forward. Just what I was looking for. Thank you!

Collapse
 
sristi27 profile image
Sristi Chowdhury

I want to simply create a read stream and pass on the image to another api.Is that possible here ? Working with multer gives no help on Heroku.

Collapse
 
lorddarthviadro profile image
LordDarthViadro

Exactly what i needed, thanks.

Collapse
 
talorlanczyk profile image
TalOrlanczyk

really important due to request been deprecated and still been download a lot