Convert an Image or an Image URL to base64 in Node.js

avatar
Borislav Hadzhiev

Last updated: Apr 5, 2024
5 min

banner

# Table of Contents

  1. How to convert an Image to base64 using Node.js
  2. Convert an Image to base64 Asynchronously using Node.js
  3. Convert an Image to base64 Asynchronously using callbacks
  4. Convert an Image URL to base64 in Node.js
  5. Convert an Image URL to base64 in Node.js using Axios

Note: if you need to convert an Image URL to base64, click on the following subheading:

The first 3 subheadings convert a local image file to base64.

# How to convert an Image to base64 using Node.js

To convert an image to base64 using Node.js:

  1. Use the fs.readdirSync() method to read the image file.
  2. Use the Buffer.from() method to convert the file to a base64 string.
  3. Optionally add the data URI prefix, e.g. 'data:image/png;base64,' + base64String
index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const fs = require('fs') function toBase64(filePath) { const img = fs.readFileSync(filePath); return Buffer.from(img).toString('base64'); } const base64String = toBase64('./house.png'); console.log(base64String); const withPrefix = 'data:image/png;base64,' + base64String; console.log(withPrefix);

convert image to base64 in node js

The code for this article is available on GitHub

The example assumes that you have a house.png file located in the same directory as your index.js script.

The code sample above uses the ES6 modules import/export syntax.

If you use CommonJS require(), use the following code sample instead.

index.js
// ๐Ÿ‘‡๏ธ if you use CommonJS require() const fs = require('fs')

We used the fs.readFileSync method to read the image file.

index.js
const img = fs.readFileSync(filePath);

The next step is to use the Buffer.from() method to create a Buffer from the file.

index.js
return Buffer.from(img).toString('base64');

Lastly, call the toString() method on the result to convert it to a base64 string.

You will most likely want to prepend the data URI prefix to the result.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const fs = require('fs') function toBase64(filePath) { const img = fs.readFileSync(filePath); return Buffer.from(img).toString('base64'); } const base64String = toBase64('./house.png'); console.log(base64String); const withPrefix = 'data:image/png;base64,' + base64String; console.log(withPrefix);
The code for this article is available on GitHub

The data URI prefix is formatted as data:<media_type>;base64, where the <media_type> placeholder is replaced by the type of the image, e.g. image/png or image/webp.

You can also shorten the example a little by passing the encoding as the second argument to the fs.readFileSync() method.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const fs = require('fs') function toBase64(filePath) { const result = fs.readFileSync(filePath, {encoding: 'base64'}); return result; } const base64String = toBase64('./house.png'); console.log(base64String); const withPrefix = 'data:image/png;base64,' + base64String; console.log(withPrefix);

The code sample above achieves the same result.

The second argument the fs.readFileSync() method takes is an options object on which we can set the encoding property to base64.

# Convert an Image to base64 Asynchronously using Node.js

If you need to convert an image to a base64 string asynchronously, use the following code sample instead.

index.js
import fs from 'fs/promises'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const fs = require('fs/promises') async function toBase64(filePath) { try { const result = await fs.readFile(filePath, { encoding: 'base64', }); return result; } catch (err) { console.log(err); } } toBase64('./house.png').then(base64String => { console.log(base64String); const withPrefix = 'data:image/png;base64,' + base64String; console.log(withPrefix); });
The code for this article is available on GitHub

The code sample above uses the ES6 modules import/export syntax.

If you use CommonJS require(), use the following import statement instead.

index.js
const fs = require('fs/promises')

Notice that we imported fs from fs/promises to be able to use the async/await syntax.

We used the fsPromises.readFile() method to read the image file asynchronously.

The method returns a Promise that fulfills with the contents of the file.

Notice that we set the encoding property to base64 in the options object.

index.js
const result = await fs.readFile(filePath, { encoding: 'base64', });

You can also prepend the data URI prefix to the base64 string.

index.js
toBase64('./house.png').then(base64String => { console.log(base64String); const withPrefix = 'data:image/png;base64,' + base64String; console.log(withPrefix); });

Notice that the toBase64() function returns a Promise.

You either have to await it or use the .then() syntax.

# Convert an Image to base64 Asynchronously using callbacks

You can also use the callback-style syntax to convert an image to base64 in Node.js.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const fs = require('fs') const filePath = './house.png'; fs.readFile( filePath, {encoding: 'base64'}, (err, base64String) => { if (err) { console.log(err); } else { console.log(base64String); const withPrefix = 'data:image/png;base64,' + base64String; console.log(withPrefix); } }, );
The code for this article is available on GitHub

Notice that we imported the fs module from fs.

The fs.readFile() method takes the following 3 parameters:

  1. The path to the file.
  2. An options object on which we can set the encoding to base64.
  3. A callback function that gets invoked once the file is read.

The callback function gets passed 2 parameters:

  1. An error. If no error occurs, the err variable is set to null.
  2. The contents of the file.

If there is no error, we log the base64 string and prepend the data URI to the string.

index.js
if (err) { console.log(err); } else { console.log(base64String); const withPrefix = 'data:image/png;base64,' + base64String; console.log(withPrefix); }

# Convert an Image URL to base64 in Node.js

If you need to convert an image URL to base64 in Node.js:

  1. Use the fetch() method to fetch the image.
  2. Use the arrayBuffer() method to convert the response to a blob.
  3. Convert the blob to a base64 string and prepend the data URI.
index.js
async function imageUrlToBase64(url) { try { const response = await fetch(url); const blob = await response.arrayBuffer(); const contentType = response.headers.get('content-type'); const base64String = `data:${contentType};base64,${Buffer.from( blob, ).toString('base64')}`; return base64String; } catch (err) { console.log(err); } } const imageUrl = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png'; imageUrlToBase64(imageUrl).then(base64String => { console.log(base64String); });

convert image url to base64

The code for this article is available on GitHub

The imageUrlToBase64() function takes the complete URL that points to the image as a parameter and converts the image URL to a base64 string.

Notice that we used the value of the content-type header when constructing the base64 string.

index.js
const blob = await response.arrayBuffer(); const contentType = response.headers.get('content-type'); const base64String = `data:${contentType};base64,${Buffer.from( blob, ).toString('base64')}`;

Make sure to either await the imageUrlToBase64() function or to use the .then() syntax because the function is asynchronous.

# Convert an Image URL to base64 in Node.js using Axios

The following example uses the axios module to fetch the image URL before converting it to a base64 string.

Make sure you have the axios module installed to be able to run the code snippet.

shell
npm init -y # with NPM npm install axios # or with YARN yarn add axios

Now import and use the axios module to convert the image URL to base64.

index.js
import axios from 'axios'; // ๐Ÿ‘‡๏ธ if you use CommonJS // const axios = require('axios'); async function imageUrlToBase64(url) { try { const response = await axios.get(url, { responseType: 'arraybuffer', }); const contentType = response.headers['content-type']; const base64String = `data:${contentType};base64,${Buffer.from( response.data, ).toString('base64')}`; return base64String; } catch (err) { console.log(err); } } const imageUrl = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png'; imageUrlToBase64(imageUrl).then(base64String => { console.log(base64String); });
The code for this article is available on GitHub

Notice that we set the responseType property to arraybuffer when fetching the image.

index.js
const response = await axios.get(url, { responseType: 'arraybuffer', });

The next step is to get the value of the content-type header so we can use it when constructing the base64 string.

index.js
const contentType = response.headers['content-type']; const base64String = `data:${contentType};base64,${Buffer.from( response.data, ).toString('base64')}`;

Make sure to access the data property on the response object when calling the Buffer.from() method as shown in the example.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev