Sometimes, we want to convert an image to a base64-encoded data URL in server-side JavaScript.
In this article, we’ll look at how to convert an image to a base64-encoded data URL in server-side JavaScript.
How to convert an image to a base64-encoded data URL in server-side JavaScript?
To convert an image to a base64-encoded data URL in server-side JavaScript, we can use a Buffer.
For instance, we write
const fs = require("fs");
const base64Encode = (file) => {
  const bitmap = fs.readFileSync(file);
  return new Buffer(bitmap).toString("base64");
};
to define the base64Encode function.
In it, we call readFileSync to read the file.
Then we convert it to a buffer with Buffer.
And then we convert it to a base64 string with toString.
Conclusion
To convert an image to a base64-encoded data URL in server-side JavaScript, we can use a Buffer.
