
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Node.js Base64 Encoding and 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.
// 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
// 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
Advertisements