Base64 Encode and Decode CLI
A small Node CLI that encodes a string to base64url or decodes a base64url string back to text, reading from an argument or stdin and printing the result.
Project
node-base64-cli
Entry point: base64.mjs
Install
node --versionRun
node base64.mjs encode "hello world"Test
node --test base64.test.mjsExpected output
Prints the base64url encoding of the input, then decodes it back to the original text.Dependencies
- node >=20
What it does
Encodes and decodes text using the URL-safe base64 alphabet without padding, which is the form used in tokens and filenames. The whole tool is a thin wrapper over Buffer with two modes.
const ALPHABET = 'base64url';
function encode(text) {
return Buffer.from(text, 'utf8').toString(ALPHABET);
}
function decode(token) {
return Buffer.from(token, ALPHABET).toString('utf8');
}
async function readStdin() {
const chunks = [];
for await (const chunk of process.stdin) chunks.push(chunk);
return Buffer.concat(chunks).toString('utf8').trim();
}
const [mode, ...rest] = process.argv.slice(2);
const input = rest.length ? rest.join(' ') : await readStdin();
if (mode === 'encode') console.log(encode(input));
else if (mode === 'decode') console.log(decode(input));
else {
console.error('usage: base64 <encode|decode> [text]');
process.exit(1);
}
Both directions accept input from an argument or from stdin, so the same command works for a quick one-off and for a pipeline that streams data.
Run and verify
node base64.mjs encode "hello world"
node base64.mjs decode aGVsbG8gd29ybGQ
Run the encode form first; the output is a URL-safe token with no padding. Pipe text in through stdin when the input contains spaces you do not want to quote.
Expected Output
With the input “hello world” the program should print the encoded token, and the decode form prints the original text back. The console.log output is:
aGVsbG8gd29ybGQ
hello world
Encoding then decoding returns the original string exactly, and the token contains no +, /, or = characters because it uses the base64url alphabet.
Limitations
It encodes and decodes UTF-8 text only; binary input must be handled by reading a Buffer instead of a string, and very large inputs are read fully into memory.