Base64 Encode/Decode a value in Nodejs

What is Base64 used for?

Base64 is an encoding algorithm that allows you to encode any binary data as printable text. It can represent any binary data in a ASCII text format that consists only of printable ASCII (American Standard Code for Information Interchange) characters. 

To encode any data in to Base64 format, the data first converted to binary data, then broken in to groups of 6 bits. Each group is then represented by a ASCII character.

Why it is called a Base64?

There are total 64 characters in the Base64 “alphabet”, so it is called as Base64. The characters used are A-Z, a-z, 0-9, +, and /.

For example:  ‘D’ is represented as ‘RA==’ in Base64, and the word ‘hello’ is represented as ‘RHVtbXk=’.

Why it is used?

  • It is a simple and efficient way to represent binary data in a text format and data can be easily transmitted over networks or saved in a text file. This is very useful for the systems, such as email, can only handle text data and not binary data.
  • It can reduces the size of the data by about 33%.
  • Many programming languages have built-in support for Base64 encoding, so you can easily use in your code.
  • There are many online tools and libraries available for encoding and decoding Base64 data.

Note : Base64 is not a secure method of encoding data, and should not be used to encode sensitive information. It is possible to easily decode base64 encoded data, so it is not recommended to be used for security purposes. It is mainly used to encode data for transmission over networks or to store data in a text format.

How to encode a value in Nodejs using Base64?

You can encode the data in Nodejs by using the global Buffer class. First create a buffer instance using the Buffer.from method. Then pass the value you want to encode as the first argument and the current encoding as the second argument.

Below is the code snippet to encode a string via Base64:

const encodedData = Buffer.from('Dummy Text', 'utf8').toString('base64')  

How to decode a value in Nodejs using Base64?

For decoding a Base64 encoding text is also possible using the global Buffer class. First create a buffer instance using the Buffer.from method. Then pass it your base64-encoded string as the first argument and the base64 encoding as the second argument. You can then translate the encoding to a UTF8 representation.

Below is the code snippet to decode a string via Base64:

const plain = Buffer.from('RHVtbXkgVGV4dA==', 'base64').toString('utf8')

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top