To convert an image to a base64-encoded data URL in sails.js or generally in the server side JavaScript, we use the buffer toString
method.
For instance, we write
const fs = require("fs");
const base64Encode = (file) => {
const bitmap = fs.readFileSync(file);
return new Buffer(bitmap).toString("base64");
};
const base64str = base64Encode("kitten.jpg");
to define the base64Encode
function.
In it, we call readFileSync
to read the file
.
And then we create a Buffer
with the returned file binary.
Then we call toString
to convert the buffer to a base64 string.