Interview Q&A / Node.js

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How do you convert a string to base64 and back in Node.js?

SHORT ANSWER

Use Buffer.from(text, "utf8").toString("base64") to encode and Buffer.from(b64, "base64").toString("utf8") to decode. Base64 is an encoding for transport, not encryption.

Explain it simply

Some channels, like email bodies or JSON, handle plain text safely but choke on raw bytes. Base64 rewrites any bytes using only 64 safe characters (A-Z, a-z, 0-9, plus and slash). It is like writing a Hindi message in Roman letters so a basic keyboard can carry it. Anyone can reverse it, so it hides nothing.

Example

js
const text = "namaste";

const b64 = Buffer.from(text, "utf8").toString("base64");
console.log(b64);                                  // bmFtYXN0ZQ==

const back = Buffer.from(b64, "base64").toString("utf8");
console.log(back);                                 // namaste

// hex and url-safe variants
console.log(Buffer.from(text).toString("hex"));    // 6e616d61737465
console.log(Buffer.from(text).toString("base64url"));

Where you meet it:

  • HTTP Basic authentication header: Authorization: Basic base64(user:password).
  • The header and payload parts of a JWT, using the base64url variant.
  • Embedding small images as data URLs.

Base64 makes data about one third larger. In browsers use btoa and atob, which work on plain strings; in Node, Buffer handles Unicode correctly.

What to say in the interview

"Buffer.from with an encoding and toString with another one converts between them. Base64 is only a reversible encoding for safe transport, so I never treat it as a way of protecting secrets."

Common mistakes

  • Thinking base64 encrypts data.
  • Forgetting the encoding argument when decoding, which treats the string as UTF-8.

#nodejs#buffer#encoding

Related questions

Practise more Node.js questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Node.js quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.