Morse Code Encoder CLI
A Node CLI that encodes text to Morse code and decodes it back, with explicit word separators, unsupported-character reporting, and tests.
Project
node-morse-code-cli
Entry point: morse.mjs
Install
node --versionRun
node morse.mjs encode "SOS HELP"Test
node --test morse.test.mjsExpected output
Prints the Morse encoding with letters separated by spaces and words by a slash, for example ... --- ... / .... . .-.. .--. for SOS HELP.Dependencies
- node >=20
What it does
Maps each letter and digit to its Morse representation, joins letters with a space and words with a slash, and decodes back. Characters outside the table raise an explicit error rather than silently emitting nothing.
const CODE = Object.fromEntries(Object.entries({
A: '.-', B: '-...', C: '-.-.', D: '-..', E: '.', F: '..-.', G: '--.', H: '....',
I: '..', J: '.---', K: '-.-', L: '.-..', M: '--', N: '-.', O: '---', P: '.--.',
Q: '--.-', R: '.-.', S: '...', T: '-', U: '..-', V: '...-', W: '.--', X: '-..-',
Y: '-.--', Z: '--..', '0': '-----', '1': '.----', '2': '..---', '3': '...--',
'4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.',
}).map(([k, v]) => [k, v]));
const DECODE = Object.fromEntries(Object.entries(CODE).map(([k, v]) => [v, k]));
export const encode = (text) => text.toUpperCase().trim().split(/\s+/)
.map((w) => w.split('').map((c) => {
if (!CODE[c]) throw new Error('unsupported character: ' + c);
return CODE[c];
}).join(' ')).join(' / ');
export const decode = (morse) => morse.split(/\s*\/\s*/)
.map((w) => w.split(/\s+/).map((g) => {
if (!DECODE[g]) throw new Error('unknown group: ' + g);
return DECODE[g];
}).join('')).join(' ');
const [mode, ...rest] = process.argv.slice(2);
console.log(mode === 'decode' ? decode(rest.join(' ')) : encode(rest.join(' ')));
Run and verify
node morse.mjs encode "SOS HELP"
Run the test command to check the implementation: node --test morse.test.mjs.
Expected Output
Each letter maps to a dot-dash group; a single space separates letters and a slash with surrounding spaces separates words:
... --- ... / .... . .-.. .--.
Limitations
Handles A-Z and 0-9 only. Punctuation and non-Latin scripts are not in the table and are rejected, which keeps the mapping explicit rather than guessed.