Node.js – Base64 Encoding & Decoding


The buffer object can be encoded and decoded into Base64 string. The buffer class can be used to encode a string into a series of bytes. The Buffer.from() method takes a string as an input and converts it into Base64.

The converted bytes can be changed again into String. The toString() method is used for converting the Base64 buffer back into the string format.

Syntax

Buffer.from(string, [encoding])
object.toString(encoding)

Parameters

The parameters are described below:

  • string − This input parameter takes input for the string that will be encoded into the base64 format.
  • encoding − This input parameter takes input for the encoding in which string will be encoded and decoded.

Example 1: Encoding into Base64

Create a file with the name "base64.js" and copy the following code snippet. After creating the file, use the command "node base64.js" to run this code.

 Live Demo

// Base64 Encoding Demo Example

// String data to be encoded
let string = "TutorialsPoint";

// Creating the buffer object with utf8 encoding
let bufferObj = Buffer.from(string, "utf8");

// Encoding into base64
let base64String = bufferObj.toString("base64");

// Printing the base64 encoded string
console.log("The encoded base64 string is:", base64String);

Output

C:\home
ode>> node base64.js The encoded base64 string is: VHV0b3JpYWxzUG9pbnQ=

Example 2: Decoding Base64 into String

 Live Demo

// Base64 Encoding Demo Example

// Base64 Encoded String
let base64string = "VHV0b3JpYWxzUG9pbnQ=";

// Creating the buffer object with utf8 encoding
let bufferObj = Buffer.from(base64string, "base64");

// Decoding base64 into String
let string = bufferObj.toString("utf8");

// Printing the base64 decoded string
console.log("The Decoded base64 string is:", string);

Output

C:\home
ode>> node base64.js The Decoded base64 string is: TutorialsPoint


Updated on: 16-Aug-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements