a blog for those who code

Friday, 31 July 2015

How to encode a string to base64 in NodeJS

In this post we are going to discuss about encoding a string to base64 or hex. In NodeJS encoding a string to base64 or hex is very easy with the help of Buffers. Buffer is nothing but an array of integers which cannot be re-sized. It is a global object which means that you need not have to write require('buffer') for using it.

Example : Encode "Hello World" to base64

var string = "Hello World";
var buffer = new Buffer(string);
var toBase64 = buffer.toString('base64');
console.log(string + " encoding to base64 is " + toBase64);

Example : Decode "Hello World" from base64

var string = "SGVsbG8gV29ybGQ=";
var buffer = new Buffer(string, 'base64');
var toAscii = buffer.toString('ascii');
console.log(string + " encoding to Ascii is " + toAscii);

Example : Encode and Decode "Hello World" to Hex

var string = "Hello World";
var buffer = new Buffer(string);
var toHex = buffer.toString('hex');
console.log(string + " encoding to hex is " + toHex);

var buffer = new Buffer(toHex, 'hex');
var toAscii = buffer.toString('ascii');
console.log("Decoding of " + toHex + " to Ascii is " + toAscii);

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us


Email *

Message *


Best Hosting Plans

CC License