How to Do Base64 Encoding in Node.js?

Node.js makes Base64 conversion easy. Use Buffer to encode or decode strings and files directly ideal for authentication and web APIs.

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.
Related

How to Get the Project Root Path in Node.js When working with large Node.js projects, you often need to find the root directory at runtime…

15 Oct, 2025

If you’re trying to run nodemon from the terminal and see the error: nodemon: command not found, it usually means the nodemon package is not…

10 Oct, 2025

Writing to files is a common task in Node.js, whether for logging, saving uploads or creating reports. Node.js has various methods through the built-in fs…

07 Oct, 2025