Base64 encode and decode strings or files using Node.js’s Buffer class. Perfect for API tokens, image handling or data formatting.

Problem

In many development scenarios like API auth, file transfer or embedding images into HTML you need to Base64 encode data. While there are third party libraries, Node.js has a native way to do Base64 encoding and decoding.

Solution

Node.js has a built in Buffer class to encode and decode data without any external modules.

Base64 encode a string

const data = ‘Hello, eSparkBiz!’;const encoded = Buffer.from(data).toString(‘base64’);

console.log(encoded); // SGVsbG8sIGVTcGFya0JpeiE=

Base64 decode a string

const decoded = Buffer.from(encoded, ‘base64’).toString(‘utf8’);console.log(decoded); // Hello, eSparkBiz!

Also Read: The Best Node.js Application Examples For Big Enterprise

Base64 encode a file (like an image)

const fs = require(‘fs’);const image = fs.readFileSync(‘logo.png’);

const base64Image = image.toString(‘base64’);

This is useful when embedding small images in HTML or sending file data over JSON or HTTP requests.

Conclusion

Base64 in Node.js is easy with the Buffer class. It’s perfect for converting strings or files to a format used in web development, APIs and secure transmission.