Sometimes, we want to read file as a base64 string with Node.js
In this article, we’ll look at how to read file as a base64 string with Node.js.
How to read file as a base64 string with Node.js?
To read file as a base64 string with Node.js, we can use the readFile method with the encoding option.
For instance, we write
const fs = require('fs').promises;
const read = async () => {
const contents = await fs.readFile('/path/to/file.jpg', {
encoding: 'base64'
});
}
to call fs.readFile with the file path and an object with the encoding property set to 'base64' to read the file as a base64 string.
It returns a promise, so we use await to get the read file contents from the resolved value.
We require the promise version of the fs module with
const fs = require('fs').promises;
Conclusion
To read file as a base64 string with Node.js, we can use the readFile method with the encoding option.