Thursday, October 11, 2018

Node JS, How to decode base64 data?

Base64 encoding is a way to convert data (typically binary) into the ASCII character set. It is important to mention here that Base64 is not an encryption or compression technique, although it can sometimes be confused as encryption due to the way it seems to obscure data. In fact, size of a Base64 encoded piece of information is 1.3333 times the actual size of your original data.

Base64 is the most widely used base encoding technique with Base16 and Base32 being the other two commonly used encoding schemes.


Encoding Base64 Strings with Node.j

The easiest way to encode Base64 strings in Node.js is via the Buffer object. In Node.js, Buffer is a global object which means that you do not need to use require statement in order to use Buffer object in your applications.

Internally Buffer is an immutable array of integers that is also capable of performing many different encodings/decodings. These include to/from UTF-8, UCS2, Base64 or even Hex encodings. As you write code that deals with and manipulates data, you'll likely be using the Buffer object at some point.
The code is seen in the previous post. Below section explain how to decode


Decoding Base64 Strings with Node.js

Decoding Base64 string is quite similar to encoding it. You have to create a new buffer object and pass two parameters to its constructor. The first parameter is the data in Base64 and second parameter is "base64". Then you simply have to call "toString" on the buffer object but this time the parameter passed to the method will be "ascii" because this is the data type that you want your Base64 data to convert to. Take a look at the following code snippet for reference.


'use strict';

let data = 'c3RhY2thYnVzZS5jb20='; 
let buff = new Buffer(data, 'base64'); 
let text = buff.toString('ascii');

console.log('"' + data + '" converted from Base64 to ASCII is "' + text + '"'); 


Decoding Base64 Strings to Binary Data

The reverse process here is very similar to how we decode Base64 strings, as we saw in an earlier section. The biggest difference is the output destination and how data is written there. Let's see the example:

'use strict';

const fs = require('fs');

let data = 'iVBORw0KGgoAAAANSUhEUgAAABkAAAATCAYAAABlcqYFAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAA' + 
'CA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAACXBIWXMAAAsTAAALEwEAmpwYAAABWWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0' + 
'YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS40LjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly' +

let buff = new Buffer(data, 'base64'); 
fs.writeFileSync('stack-abuse-logo-out.png', buff);

console.log('Base64 image data converted to file: stack-abuse-logo-out.png');


References:
https://stackabuse.com/encoding-and-decoding-base64-strings-in-node-js/

No comments:

Post a Comment