Skip to main content

How to download an image to file on disk when scraping a website

2/7/20191 min read

Recently I was recovering data from one of my websites that had been unceremoniously taken down while I was on holidays when I got stomped for a little while on how to scrape an image and save it to file using NodeJS.

Let’s say you are using puppeteer and you have the image URL for the image you want to save to disk.

I knew I could use the fs.writeFilebut I was trying to figure out how to get it from a http response to something that I could write to file. I tried to parse it into a blob, but then I discovered you can just pipe the response body directly into fs.createWriteStream. My code ended up looking like this:

const imageUrl = '';
const imageDirAndName = './downloaded-img.jpg';

    .then(response => response.body.pipe(fs.createWriteStream(imageDirAndName)).on('close', () => console.log('image downloaded')))
    .catch(err => console.error(err.stack));
© 2021 by Madole.
GitHub Repository
Last build: 1662286611335