murvinlai murvinlai - 4 months ago 23
Node.js Question

How to do Base64 encoding in node.js?

Does node.js have built-in base64 encoding yet?

The reason why I ask this is that

can only output hex, binary or ascii data. For example:

var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv);
var ciph = cipher.update(plaintext, 'utf8', 'hex');
ciph +='hex');

var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv);
var txt = decipher.update(ciph, 'hex', 'utf8');
txt +='utf8');

According to the docs,
can output base64-encoded data. However,
doesn't support base64. I tried and it will break.

If I do this:

var ciph = cipher.update(plaintext, 'utf8', 'base64');
ciph +='hex');

Then what should I use for decryption? Hex or base64?

Therefore, I'm looking for a function to base64-encode my encrypted hex output.



Buffers can be used for taking a string or piece of data and doing base64 encoding of the result. For example:

> console.log(new Buffer("Hello World").toString('base64'));
> console.log(new Buffer("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'))
Hello World

Buffers are a global object, so no require is needed. Buffers created with strings can take an optional encoding parameter to specify what encoding the string is in. The available toString and Buffer constructor encodings are as follows:

'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and will strip the high bit if set.

'utf8' - Multi byte encoded Unicode characters. Many web pages and other document formats use UTF-8.

'ucs2' - 2-bytes, little endian encoded Unicode characters. It can encode only BMP(Basic Multilingual Plane, U+0000 - U+FFFF).

'base64' - Base64 string encoding.

'binary' - A way of encoding raw binary data into strings by using only the first 8 bits of each character. This encoding method is deprecated and should be avoided in favor of Buffer objects where possible. This encoding will be removed in future versions of Node.