How to Download an Image from URL using Node

Updated onbyAlan Morel
How to Download an Image from URL using Node

Images are crucial part of the experience on the web.

As resources, images are pointed to using URLs, meaning if you have a URL, you can download the image.

In this post, we'll learn how to download an image from a URL using Node.

Download an image from a URL

To download an image, first we need a URL:

JAVASCRIPT
const url = "https://sabe.io/images/saturn.png";

Since we know we will eventually save this file to disk, let's import the fs module:

JAVASCRIPT
import { promises as fs } from "fs"; const url = "https://sabe.io/images/saturn.png";

Now, we can make use of the native fetch function in Node, so we don't need to import libraries like axios or requests.

Simply pass in the URL to make the request:

JAVASCRIPT
import { promises as fs } from "fs"; const url = "https://sabe.io/images/saturn.png"; const response = await fetch(url);

Now comes the tricky part. We need to take this response, convert it to a blob. With this blob, we then have to convert it to an ArrayBuffer, then finally create a normal Buffer from this ArrayBuffer.

The goal is ultimately, to be able to take this Buffer and write it to disk.

Here's how this looks:

JAVASCRIPT
import { promises as fs } from "fs"; const url = "https://sabe.io/images/saturn.png"; const response = await fetch(url); const blob = await response.blob(); const arrayBuffer = await blob.arrayBuffer(); const buffer = Buffer.from(arrayBuffer);

Finally, now that we have our Buffer, we can write it to a file with a name of your choice:

JAVASCRIPT
import { promises as fs } from "fs"; const url = "https://sabe.io/images/saturn.png"; const response = await fetch(url); const blob = await response.blob(); const arrayBuffer = await blob.arrayBuffer(); const buffer = Buffer.from(arrayBuffer); await fs.writeFile("./saturn.png", buffer);

This works, but we can convert this into a reusable function for repeated usage:

JAVASCRIPT
import { promises as fs } from "fs"; const downloadImage = async (url, path) => { const response = await fetch(url); const blob = await response.blob(); const arrayBuffer = await blob.arrayBuffer(); const buffer = Buffer.from(arrayBuffer); await fs.writeFile(path, buffer); } await downloadImage("https://sabe.io/images/saturn.png", "./saturn.png");

And that is how you use the native Node fetch function to download an image asynchronously using the await/async syntax.

Conclusion

In this post, we learned how to asynchronously download an image using Node without any additional libraries.

Simply use the native fetch function and convert the formats a few times to get a buffer that you can write to disk.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.