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
xxxxxxxxxx
1
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.
In this example, we create a reusable function that converts image to base64 encoded string.
xxxxxxxxxx
1
const fs = require('fs');
2
3
// relative path to the img
4
const filePath = './img.jpg';
5
6
// reusable arrow function to encode file data to base64 encoded string
7
const convertBase64 = (path) => {
8
// read binary data from file
9
const bitmap = fs.readFileSync(path);
10
// convert the binary data to base64 encoded string
11
return bitmap.toString('base64');
12
};
13
14
15
// Usage example
16
const result = convertBase64('img.jpg');
17