How do I create a base64 JSON encoded strings in nodejs?
I tried this and it didn't work.
var buff = new Buffer({"hello":"world"}).toString("base64");
Is this it?
var buff = new Buffer(JSON.stringify({"hello":"world"})).toString("base64");
World's simplest base64 JSON encoder for web developers and programmers. Just paste your JSON data structure in the form below, press Base64 Encode JSON button, and you get a base64-encoded JSON document.
This can be done using the Buffer. from() method that accepts the string to be converted and the current encoding of the string. This encoding can be specified as “utf8”. The converted bytes can then be returned as a base64 using the toString() method.
Base64 is a binary-to-text encoding scheme used to transport data. The encoding is necessary when the transfer medium is not able to handle binary data. This binary data is then translated to a text representation (base64) and transferred as text.
btoa(): accepts a string where each character represents an 8bit byte. If you pass a string containing characters that cannot be represented in 8 bits, it will probably break. Probably that's why btoa is deprecated.
var buff = new Buffer(JSON.stringify({"hello":"world"})).toString("base64");
To complete @ladenedge's comment for clarity reasons:
var buff = Buffer.from(JSON.stringify({"hello":"world"})).toString("base64")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With