EN
Node.js - convert image to base64
0
points
In this article, we would like to show you how to convert image to base64 in Node.js.
1. Import fs module
const fs = require('fs');
2. Use:
-
fs.readFileSync()to read the data from file toString()method with specified'base64'argument to receive base64 encoded string.
Practical example
In this example, we create a reusable function that converts image to base64 encoded string.
const fs = require('fs');
// relative path to the img
const filePath = './img.jpg';
// reusable arrow function to encode file data to base64 encoded string
const convertBase64 = (path) => {
// read binary data from file
const bitmap = fs.readFileSync(path);
// convert the binary data to base64 encoded string
return bitmap.toString('base64');
};
// Usage example
const result = convertBase64('img.jpg');