Logo

How can I do Base64 encoding in Node.js?

In Node.js, you can easily perform Base64 encoding using the built-in Buffer class. Below are the most common methods:

1. Encoding a String to Base64

// Sample text const text = 'Hello, Node.js!'; // Create a buffer from the string const buffer = Buffer.from(text, 'utf-8'); // Convert buffer to Base64 string const base64String = buffer.toString('base64'); console.log('Base64 Encoded:', base64String); // e.g., SGVsbG8sIE5vZGUuanMh

Key Points:

  • Buffer.from(string, 'utf-8'): Creates a buffer from a UTF-8 string.
  • .toString('base64'): Outputs the Base64-encoded representation of the buffer.

2. Decoding Base64 Back to a String

To reverse the operation (Base64 -> original string), do the following:

// Assuming you have a base64-encoded string const base64String = 'SGVsbG8sIE5vZGUuanMh'; // Convert from Base64 to Buffer const decodedBuffer = Buffer.from(base64String, 'base64'); // Convert buffer to original string const originalString = decodedBuffer.toString('utf-8'); console.log('Decoded String:', originalString); // e.g., Hello, Node.js!

3. Encoding/Decoding Binary Data

If you’re dealing with binary files (images, PDFs, etc.), you can read the file into a buffer, then call .toString('base64'). For example:

const fs = require('fs'); // Read a binary file into a buffer const fileBuffer = fs.readFileSync('./image.png'); // Encode buffer to Base64 const base64Image = fileBuffer.toString('base64'); // You can also decode back to binary if needed: const decodedBuffer = Buffer.from(base64Image, 'base64'); // Then save it as a file fs.writeFileSync('./decoded_image.png', decodedBuffer);

4. Common Use Cases

  1. Embedding Assets in HTML or CSS (inline images, fonts).
  2. Sending Binary Data over text-based protocols (e.g., JSON, XML).
  3. Storing Small Binaries in databases where a text field is required.

5. Summary

  • To Encode: Buffer.from(stringOrBuffer).toString('base64')
  • To Decode: Buffer.from(base64String, 'base64').toString('utf-8')
  • Works similarly for both text and binary data, though you’ll need to handle buffers directly when dealing with files.

This built-in Buffer API provides a straightforward way to convert data to and from Base64 in Node.js without external libraries.

Recommended Resource

CONTRIBUTOR
TechGrind