Use-Cases of this code snippet
- Know how to decode base64 in Node.
- Know how to encode to base64 in Node.
Encoding and decoding base64 data in Node.js can be done using the Buffer module.
Node.js does not support the standard Javascript methods of atob() and btoa() for base64 conversions.
Base64 encoding and decoding can be done in Node.js using the Buffer module. This module is loaded by default, hence no import is required.
The Buffer class can be used to manipulate streams of binary data in Node. The Buffer.from() method can create a buffer (binary data) from a given string in a specified encoding. toString() method can then be used on this buffer object to decode it as required.
Encoding to Base64 in Node.js
To convert a string to base64, we need to create a buffer from the given string. This buffer can then be decoded as base64.
// UTF8 input string
let str = "UsefulAngle";
// create buffer from string
let binaryData = Buffer.from(str, "utf8");
// decode buffer as base64
let base64Data = binaryData.toString("base64");
// "VXNlZnVsQW5nbGU="
console.log(base64Data);
Note that the encoding of the string can also be set in the Buffer.from method. Mostly we deal with UFT8 strings, but any other encoding as be specified as well.
Decoding Base64 in Node.js
To decode a base64 string, we need to create a buffer from the given base64 string. This buffer can then be decoded into a UTF8 string.
// base64 encoded input string
let str = "VXNlZnVsQW5nbGU=";
// create buffer from base64 string
let binaryData = Buffer.from(str, "base64");
// decode buffer as utf8
let base64Dec = binaryData.toString("utf8");
// "UsefulAngle"
console.log(base64Dec);