How to do Base64 encoding in Node.js

 

1. Built-in Methods for Base64 Encoding

Node.js provides a built-in functionality for base64 encoding through the Buffer class. The following section discusses how to use the Buffer class to encode strings in base64.

1.1 Base64 Encoding using Buffer Class

The Buffer class in Node.js is a global class and does not require an import or include statement. Here’s an example of how to use the Buffer class to base64 encode a string:

function base64Encode(inputString) {
  let bufferObj = Buffer.from(inputString, "utf8");
  return bufferObj.toString("base64");
}

// Calling the function with an example string
let encodedString = base64Encode("Hello, World!");
console.log(encodedString);

Output:

SGVsbG8sIFdvcmxkIQ==

This function creates a buffer object from the input string, specifying “utf8” as the character encoding, and then converts the buffer to a base64 string using the toString('base64') method.

Similarly, we can decode a base64 string back to its original text:

function base64Decode(encodedString) {
  let bufferObj = Buffer.from(encodedString, "base64");
  return bufferObj.toString("utf8");
}

// Decoding the previously encoded string
let decodedString = base64Decode(encodedString);
console.log(decodedString);

Output:

Hello, World!

 

2. Third-Party Libraries for Base64 Encoding

Aside from using Node.js’s native Buffer class, you can also utilize third-party libraries that provide additional functionalities and a more abstracted interface. A popular library for base64 encoding is js-base64. Here’s how you would use it:

Note: Before using the following code make sure to install the library using npm: npm install js-base64.

const { Base64 } = require('js-base64');

function base64EncodeUsingLibrary(inputString) {
  return Base64.encode(inputString);
}

let encodedUsingLib = base64EncodeUsingLibrary("Encode with js-base64!");
console.log(encodedUsingLib);

Output:

RW5jb2RlIHdpdGgganMtYmFzZTY0IQ==

And to decode the string:

function base64DecodeUsingLibrary(encodedString) {
  return Base64.decode(encodedString);
}

let decodedUsingLib = base64DecodeUsingLibrary(encodedUsingLib);
console.log(decodedUsingLib);

Output:

Encode with js-base64!

 

3. Custom Base64 encoding

Fancy a bit of manual processing? A custom base64 encoding function, although less efficient than Buffer methods, could be written for educational purposes:

function customBase64Encode(input) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    let encoded = '';
    let padding = '';

    while (input.length % 3) {
        input += '\0';
        padding += '=';
    }

    for (let i = 0; i < input.length; i += 3) {
        const n = (input.charCodeAt(i) << 16) + (input.charCodeAt(i + 1) << 8) + input.charCodeAt(i + 2);
        encoded += chars.charAt((n >>> 18) & 63) + chars.charAt((n >>> 12) & 63) + chars.charAt((n >>> 6) & 63) + chars.charAt(n & 63);
    }

    return encoded.substring(0, encoded.length - padding.length) + padding;
}

// Example usage:
const customEncoded = customBase64Encode('Hello, World!');
console.log(customEncoded);

Output:

SGVsbG8sIFdvcmxkIQ==

 

4. Summary and Conclusions

In this tutorial, we’ve looked at different ways to perform base64 encoding in Node.js, showing that you can use the native Buffer class for simplicity and performance or opt for a third-party library like js-base64 for its extended features and ease of use. Whether you are handling form data, implementing authentication mechanisms, or dealing with file uploads, knowing how to work with base64 encoding is an invaluable skill in a Node.js developer’s toolkit.

References