Encode & Decode Base64

English Espa├▒ol

Base64 in NodeJS (Encode/Decode)



Node.js provides a built-in Buffer class that makes it easy to work with binary data and encoding schemes like Base64.

Encoding to Base64

To encode data to Base64, you'll need to create a Buffer object and then convert it to a Base64 string:


const buffer = Buffer.from('Hello World');
                const base64 = buffer.toString('base64');
                console.log(base64); // Output: 'SGVsbG8gV29ybGQ='

Decode from Base64

To decode a Base64 string, create a new Buffer object and specify the 'base64' encoding:


const bufferFromBase64 = Buffer.from('SGVsbG8gV29ybGQ=', 'base64');
                const decoded = bufferFromBase64.toString();
                console.log(decoded); // Output: 'Hello World'

Encoding an Image to Base64

You can easily encode an image to Base64 using the built-in fs (File System) module and the Buffer class:


const fs = require('fs');
                const imageBuffer = fs.readFileSync('path/to/your/image.jpg'); // read the image file into a Buffer
                const base64Image = imageBuffer.toString('base64');