Yo! Base64 Encode logoYo! Base64 Encode
Node.js

How to Base64 Encode a String in Node.js

Learn how to encode strings to Base64 in Node.js with practical examples and best practices. Includes Buffer handling, stream processing, and error management.

By Ishan Karunaratne2 min read

Need to encode strings to Base64 in Node.js? Here's your complete guide with practical examples and best practices for both string and buffer handling.

Quick Start: Basic String Encoding

Let's start with the simplest way to encode a string:

JAVASCRIPT
// Basic string encoding
const text = 'Hello, World!';
const encoded = Buffer.from(text).toString('base64');
console.log(encoded); // Output: SGVsbG8sIFdvcmxkIQ==

// Decode to verify
const decoded = Buffer.from(encoded, 'base64').toString('utf-8');
console.log(decoded); // Output: Hello, World!

String Encoding Functions

Create these utility functions for common encoding tasks:

JAVASCRIPT
function encodeString(text) {
    try {
        const encoded = Buffer.from(text).toString('base64');
        return {
            success: true,
            encoded,
            originalLength: text.length,
            encodedLength: encoded.length
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

function encodeWithValidation(text) {
    // Input validation
    if (!text) {
        return {
            success: false,
            error: 'Empty input'
        };
    }

    // Check input size
    if (text.length > 1024 * 1024) { // 1MB limit
        return {
            success: false,
            error: 'Input too large'
        };
    }

    return encodeString(text);
}

Handling Different Character Sets

JAVASCRIPT
class StringEncoder {
    constructor(encoding = 'utf8') {
        this.encoding = encoding;
    }

    encode(text) {
        try {
            const buffer = Buffer.from(text, this.encoding);
            const encoded = buffer.toString('base64');

            return {
                success: true,
                encoded,
                originalSize: buffer.length,
                encodedSize: encoded.length,
                encoding: this.encoding
            };
        } catch (error) {
            return {
                success: false,
                error: error.message
            };
        }
    }

    encodeMultiple(strings) {
        const results = [];
        const errors = [];

        strings.forEach((str, index) => {
            const result = this.encode(str);
            if (result.success) {
                results.push({
                    index,
                    encoded: result.encoded
                });
            } else {
                errors.push({
                    index,
                    error: result.error
                });
            }
        });

        return {
            success: errors.length === 0,
            results,
            errors
        };
    }
}

Working with Files

Stream-Based File Encoding

JAVASCRIPT
const fs = require('fs');
const { Transform } = require('stream');

class Base64EncodeStream extends Transform {
    constructor(options = {}) {
        super(options);
        this.remainder = null;
    }

    _transform(chunk, encoding, callback) {
        let buffer = chunk;
        if (this.remainder) {
            buffer = Buffer.concat([this.remainder, chunk]);
            this.remainder = null;
        }

        const remainderLength = buffer.length % 3;
        if (remainderLength) {
            this.remainder = buffer.slice(buffer.length - remainderLength);
            buffer = buffer.slice(0, buffer.length - remainderLength);
        }

        this.push(buffer.toString('base64'));
        callback();
    }

    _flush(callback) {
        if (this.remainder) {
            this.push(this.remainder.toString('base64'));
        }
        callback();
    }
}

function encodeFile(inputPath, outputPath) {
    return new Promise((resolve, reject) => {
        const readStream = fs.createReadStream(inputPath);
        const writeStream = fs.createWriteStream(outputPath);
        const encoder = new Base64EncodeStream();

        readStream
            .pipe(encoder)
            .pipe(writeStream)
            .on('finish', () => {
                resolve({
                    success: true,
                    inputPath,
                    outputPath
                });
            })
            .on('error', (error) => {
                reject({
                    success: false,
                    error: error.message
                });
            });
    });
}

Handling Binary Data

JAVASCRIPT
class BinaryEncoder {
    static encode(buffer) {
        try {
            if (!Buffer.isBuffer(buffer)) {
                buffer = Buffer.from(buffer);
            }

            return {
                success: true,
                encoded: buffer.toString('base64'),
                originalSize: buffer.length
            };
        } catch (error) {
            return {
                success: false,
                error: error.message
            };
        }
    }

    static async encodeFromFile(filePath) {
        try {
            const data = await fs.promises.readFile(filePath);
            return this.encode(data);
        } catch (error) {
            return {
                success: false,
                error: error.message
            };
        }
    }
}

Web Application Examples

API Request Handling

JAVASCRIPT
const express = require('express');
const multer = require('multer');
const upload = multer();

const app = express();

class APIEncoder {
    static encodeRequestBody(req, res, next) {
        try {
            if (req.body) {
                const encoded = Buffer.from(
                    JSON.stringify(req.body)
                ).toString('base64');
                
                req.encodedBody = encoded;
            }
            next();
        } catch (error) {
            next(error);
        }
    }

    static async handleFileUpload(file) {
        try {
            const encoded = file.buffer.toString('base64');
            return {
                success: true,
                filename: file.originalname,
                mimetype: file.mimetype,
                encoded,
                size: {
                    original: file.size,
                    encoded: encoded.length
                }
            };
        } catch (error) {
            return {
                success: false,
                error: error.message
            };
        }
    }
}

// Example usage with Express
app.post('/encode', 
    upload.single('file'),
    APIEncoder.encodeRequestBody,
    async (req, res) => {
        const result = {
            body: req.encodedBody
        };

        if (req.file) {
            result.file = await APIEncoder.handleFileUpload(req.file);
        }

        res.json(result);
    }
);

Performance Optimization

JAVASCRIPT
class OptimizedEncoder {
    constructor(options = {}) {
        this.chunkSize = options.chunkSize || 1024 * 1024; // 1MB
        this.concurrency = options.concurrency || 4;
    }

    async encodeChunked(buffer) {
        const chunks = [];
        for (let i = 0; i < buffer.length; i += this.chunkSize) {
            chunks.push(
                buffer.slice(i, Math.min(i + this.chunkSize, buffer.length))
            );
        }

        const encodedChunks = await Promise.all(
            chunks.map(chunk => {
                return new Promise((resolve) => {
                    setImmediate(() => {
                        resolve(chunk.toString('base64'));
                    });
                });
            })
        );

        return {
            success: true,
            encoded: encodedChunks.join(''),
            chunks: chunks.length
        };
    }

    async encodeParallel(buffers) {
        const results = await Promise.all(
            buffers.map(async (buffer, index) => {
                try {
                    const result = await this.encodeChunked(buffer);
                    return {
                        index,
                        ...result
                    };
                } catch (error) {
                    return {
                        index,
                        success: false,
                        error: error.message
                    };
                }
            })
        );

        return {
            success: results.every(r => r.success),
            results
        };
    }
}

Best Practices and Error Handling

JAVASCRIPT
class EncodingValidator {
    static validate(input) {
        if (!input) {
            return {
                valid: false,
                error: 'Empty input'
            };
        }

        if (typeof input === 'string' && input.length > 1024 * 1024) {
            return {
                valid: false,
                error: 'Input too large'
            };
        }

        return { valid: true };
    }
}

class SafeEncoder {
    static encode(input) {
        const validation = EncodingValidator.validate(input);
        if (!validation.valid) {
            return {
                success: false,
                error: validation.error
            };
        }

        try {
            const encoded = Buffer.from(input).toString('base64');
            return {
                success: true,
                encoded,
                validation
            };
        } catch (error) {
            return {
                success: false,
                error: error.message
            };
        }
    }
}

Conclusion

Node.js provides robust tools for Base64 encoding through its Buffer API. Whether you're working with strings, files, or binary data, the examples above demonstrate how to handle Base64 encoding efficiently and safely. Remember to always validate input, handle errors appropriately, and consider performance implications when working with large data sets.

Frequently Asked Questions

Q: What's the difference between Buffer.from() and new Buffer()? A: Always use Buffer.from() as new Buffer() is deprecated for security reasons. Buffer.from() provides safer memory allocation.

Q: How do I handle large files without memory issues? A: Use the stream-based approach with Base64EncodeStream for large files to prevent loading the entire file into memory.

Q: Can I encode binary data directly? A: Yes, use Buffer.from() with binary data, and it will automatically handle the encoding properly.

Q: How do I handle Unicode characters correctly? A: Specify 'utf8' encoding when creating the Buffer: Buffer.from(text, 'utf8').toString('base64').

Q: Is Base64 encoding secure for sensitive data? A: No, Base64 is encoding, not encryption. Use proper encryption methods for sensitive data.

Encode text to Base64 now , paste it into the free encoder and get the result instantly.
Ishan Karunaratne

Ishan Karunaratne

Software & DevOps engineer

I build and maintain Yo! Base64 Encode and write these guides from hands-on work with encoding in real systems, API payloads, JWTs, CI pipelines, and the occasional 2am debugging session.

More of my writing at techearl.com