-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathwc.mjs
More file actions
34 lines (27 loc) · 1.22 KB
/
wc.mjs
File metadata and controls
34 lines (27 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { program } from 'commander';
import process from 'node:process';
import { promises as fs } from 'node:fs';
program
.name('wc')
.description('Counts the number of lines, words, and characters in a file.')
.argument('<path>', 'The path to the file to analyze')
.option('-l, --lines', 'Only count lines')
.option('-w, --words', 'Only count words')
.option('-c, --characters', 'Only count characters');
program.parse();
const argv = program.args;
if (argv.length != 1) {
console.error(
`Expected exactly 1 argument (a path) to be passed but got ${argv.length}.`);
process.exit(1);
}
const path = argv[0];
const options = program.opts();
let showLines = options.lines || (!options.words && !options.characters);
let showWords = options.words || (!options.lines && !options.characters);
let showCharacters = options.characters || (!options.lines && !options.words);
const content = await fs.readFile(path, 'utf-8');
const lineCount = content.split('\n').filter(Boolean).length;
const wordCount = content.split(' ').filter(Boolean).length;
const characterCount = content.length;
console.log(` ${showLines ? lineCount : ''} ${showWords ? wordCount : ''} ${showCharacters ? characterCount : ''} ${path}`);