Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

base64 JSON encoded strings in nodejs

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");
like image 398
ThomasReggi Avatar asked Mar 19 '14 18:03

ThomasReggi


People also ask

Can you base64 encode JSON?

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.

How do I encode a string in node JS?

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.

What is base64 in Nodejs?

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.

Is BTOA deprecated?

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.


2 Answers

var buff = new Buffer(JSON.stringify({"hello":"world"})).toString("base64");
like image 125
ThomasReggi Avatar answered Oct 16 '22 21:10

ThomasReggi


To complete @ladenedge's comment for clarity reasons:

var buff = Buffer.from(JSON.stringify({"hello":"world"})).toString("base64")
like image 21
cpres Avatar answered Oct 16 '22 21:10

cpres