Skip to content

Commit 062fdd3

Browse files
weshaanpascalecu
authored andcommitted
Add Base64 Encode Decode in JavaScript (TheRenegadeCoder#4996)
1 parent f5fa701 commit 062fdd3

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#!/usr/bin/env node
2+
3+
function usageAndExit() {
4+
console.error("Usage: please provide a mode and a string to encode/decode");
5+
process.exit(1);
6+
}
7+
8+
function isValidBase64(str) {
9+
// Check length multiple of 4
10+
if (str.length % 4 !== 0) return false;
11+
// Only A–Z, a–z, 0–9, +, /, = allowed
12+
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(str)) return false;
13+
// = only allowed at end, at most two
14+
const idx = str.indexOf("=");
15+
if (idx !== -1 && idx < str.length - 2) {
16+
// e.g. “ab==cd” invalid
17+
return false;
18+
}
19+
return true;
20+
}
21+
22+
function encodeBase64(input) {
23+
// Use Buffer in Node.js
24+
return Buffer.from(input, "ascii").toString("base64");
25+
}
26+
27+
function decodeBase64(input) {
28+
// Validate first
29+
if (!isValidBase64(input)) {
30+
usageAndExit();
31+
}
32+
// Buffer will ignore invalid trailing bits
33+
return Buffer.from(input, "base64").toString("ascii");
34+
}
35+
36+
function main() {
37+
const args = process.argv.slice(2);
38+
if (args.length < 2) {
39+
usageAndExit();
40+
}
41+
const mode = args[0];
42+
const text = args[1];
43+
44+
if (!text) {
45+
usageAndExit();
46+
}
47+
48+
if (mode === "encode") {
49+
console.log(encodeBase64(text));
50+
} else if (mode === "decode") {
51+
console.log(decodeBase64(text));
52+
} else {
53+
usageAndExit();
54+
}
55+
}
56+
57+
if (require.main === module) {
58+
main();
59+
}
60+

0 commit comments

Comments
 (0)