Last updated: Apr 5, 2024
Reading timeยท5 min

Note: if you need to convert an Image
URLto base64, click on the following subheading:
The first 3 subheadings convert a local image file to base64.
To convert an image to base64 using Node.js:
fs.readdirSync() method to read the image file.Buffer.from() method to convert the file to a base64 string.'data:image/png;base64,' + base64Stringimport 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 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.
// ๐๏ธ if you use CommonJS require() const fs = require('fs')
We used the fs.readFileSync method to read the image file.
const img = fs.readFileSync(filePath);
The next step is to use the Buffer.from() method to create a Buffer from the
file.
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.
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 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.
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.
If you need to convert an image to a base64 string asynchronously, use the following code sample instead.
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 sample above uses the ES6 modules import/export syntax.
If you use CommonJS require(), use the following import statement instead.
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.
const result = await fs.readFile(filePath, { encoding: 'base64', });
You can also prepend the data URI prefix to the base64 string.
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.
You can also use the callback-style syntax to convert an image to base64 in Node.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); } }, );
Notice that we imported the fs module from fs.
The fs.readFile() method takes the following 3 parameters:
options object on which we can set the encoding to base64.The callback function gets passed 2 parameters:
err variable is set to null.If there is no error, we log the base64 string and prepend the data URI to the string.
if (err) { console.log(err); } else { console.log(base64String); const withPrefix = 'data:image/png;base64,' + base64String; console.log(withPrefix); }
If you need to convert an image URL to base64 in Node.js:
fetch() method to fetch the image.arrayBuffer() method to convert the response to a blob.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); });

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.
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.
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.
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.
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); });
Notice that we set the responseType property to arraybuffer when fetching
the image.
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.
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.
You can learn more about the related topics by checking out the following tutorials: