1
  • I have a requirement in which I need to convert an input text to a png/jpeg file and then convert to base64 string and send as an input to an API.
  • I cannot use node.js fs module since I cannot physically create files.
  • So I was trying to user node.js Buffer module to achieve the same.
  • But the issue I'm facing is, I cannot add extension to it(I don't know if there is any such option). Is there any other way of doing so?

Below is the code I tried...

function textToFileBase64(str){
    var buf = Buffer.from(str, 'utf-8');
    return buf.toString('base64');

}

The only problem with the above code is that it creates a file without extension and even if I need the file as abc.png, it says the file is damaged when I open it.

Avinash
  • 2,003
  • 2
  • 17
  • 15
  • I got this code from https://stackoverflow.com/questions/43487543/writing-binary-data-using-node-js-fs-writefile-to-create-an-image-file var img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0" + "NAAAAKElEQVQ4jWNgYGD4Twzu6FhFFGYYNXDUwGFpIAk2E4dHDRw1cDgaCAASFOffhEIO" + "3gAAAABJRU5ErkJggg=="; // strip off the data: url prefix to get just the base64-encoded bytes var data = img.replace(/^data:image\/\w+;base64,/, ""); var buf = new Buffer(data, 'base64'); Just wanted to understand how to create the base64 code of an image having the text I need. – Avinash Feb 17 '20 at 10:05

0 Answers0