Base64 encoding and decoding can be done in Node.js using the Buffer object.
Encoding the original string to base64: The Buffer class in Node.js can be used to convert a string to a series of bytes. This can be done using the Buffer.from() method that accepts the string to be converted and the current encoding of the string. This encoding can be specified as “utf8”.
The converted bytes can then be returned as a base64 using the toString() method. This method accepts a parameter that specifies the encoding needed during conversion. In this case, “base64” is specified as the encoding to be used. Thus, this method converts any string to the base64 format.
// Create buffer object, specifying utf8 as encoding let bufferObj = Buffer.from(originalString, "utf8"); // Encode the Buffer as a base64 string let base64String = bufferObj.toString("base64");
The encoded base64 string is: R2Vla3Nmb3JHZWVrcw==
Decoding base64 to original string: The Buffer can also be used to convert the base64 string back to utf8 encoding. The Buffer.from() method is again used to convert the base64 string back to bytes, however, this time specifying the current encoding as “base64”.
The converted bytes can then be returned as the original utf8 string using the toString() method. In this case, “utf8” is specified as the encoding to be used. Thus, this method converts the base64 to its original utf9 format.
// Create a buffer from the string let bufferObj = Buffer.from(base64string, "base64"); // Encode the Buffer as a utf8 string let decodedString = bufferObj.toString("utf8");
The decoded string: GeeksforGeeks
- Encoding and Decoding Base64 Strings in Python
- How to convert an image to base64 encoding in PHP?
- Nodejs | Automatic restart NodeJs server with nodemon
- jQuery deferred.done() Method
- How to validate if input in input field has base64 encoded string using express-validator ?
- HTML | URL Encoding
- Web TextEncoder API | TextEncoder encoding property
- HTTP headers | Accept-Encoding
- HTTP headers | Content-Encoding
- HTTP headers | Transfer-Encoding
- What is Internal Storage Encoding of Characters(ISCII)?
- ISCII Encoding
- Signup Form Using Nodejs and MongoDB
- Difference between NodeJS and AngularJS
- Nodejs | authentication using Passportjs and passport-local-mongoose
- 7 Famous Apps Built on NodeJS: Reasons and Benefits
- Which One is Most Demanding Back-End Web Framework between Laravel , NodeJS and Django ?
- NodeJs CRUD Operations Using Mongoose and MongoDB Atlas
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.