Text Wrapping CLI
A Node CLI that wraps a paragraph to a target width without breaking words, and optionally indents each wrapped line for quote or code formatting.
Project
node-text-wrap-cli
Entry point: wrap.mjs
Install
node --versionRun
node wrap.mjs 20 "The quick brown fox jumps over the lazy dog"Test
node --test wrap.test.mjsExpected output
Prints the text wrapped to the given width with each line no longer than the limit.Dependencies
- node >=20
What it does
Wraps a paragraph to a target column width without splitting words, which is the common need for formatting commit bodies, emails, and quoted text.
export function wrap(text, width, { indent = '' } = {}) {
const words = text.split(/\s+/).filter(Boolean);
const lines = [];
let line = '';
for (const word of words) {
if (!line) line = word;
else if ((line + ' ' + word).length <= width) line += ' ' + word;
else { lines.push(indent + line); line = word; }
}
if (line) lines.push(indent + line);
return lines.join('\n');
}
const width = Number(process.argv[2]);
const text = process.argv.slice(3).join(' ');
if (!Number.isInteger(width) || width < 1) { console.error('usage: wrap <width> <text>'); process.exit(1); }
console.log(wrap(text, width));
An optional indent prefixes each line, and words longer than the width are left intact rather than broken mid-word.
Run and verify
node wrap.mjs 20 "The quick brown fox jumps over the lazy dog"
Pass the width first and the text after it; a word longer than the width occupies its own line rather than being split.
Expected Output
For a width of twenty the sentence should wrap into short lines with no word broken. The output is:
The quick brown fox
jumps over the lazy
dog
No line exceeds the requested width unless a single word is longer, and the indent option prefixes every produced line.
Limitations
Wrapping is greedy rather than balanced, so it may leave a short last line; a balanced algorithm would even out the lines.