-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathwc.js
More file actions
66 lines (53 loc) · 1.71 KB
/
wc.js
File metadata and controls
66 lines (53 loc) · 1.71 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { program } from "commander";
import { promises as fs } from "node:fs";
//config the program
program
.name("wc")
.description(
"The wc utility displays the number of lines, words, and bytes contained in each input file, or standard input"
)
.option("-l, --lines", "count lines only")
.option("-w, --words", "count words only")
.option("-c, --bytes", "count bytes only")
.argument("<path...>", "The file paths to process");
//interpret the program
program.parse();
//initialise totals
let totalLines = 0;
let totalWords = 0;
let totalBytes = 0;
//check for flags
const hasLineFlag = program.opts().lines;
const hasWordFlag = program.opts().words;
const hasBytesFlag = program.opts().bytes;
// create output format function to avoid repetition
function formatOutput(lines, words, bytes, path) {
if (hasLineFlag) {
console.log(`${lines} ${path}`);
} else if (hasWordFlag) {
console.log(`${words} ${path}`);
} else if (hasBytesFlag) {
console.log(`${bytes} ${path}`);
} else {
console.log(`${lines} ${words} ${bytes} ${path}`);
}
}
//process each file
for (const path of program.args) {
//read the file
const content = await fs.readFile(path, "utf-8");
//count lines
const lines = content.split("\n").length - 1;
//count words (split by any whitespace)
const words = content.split(/\s+/).filter((word) => word.length > 0).length;
//count bytes correctly especially important for non-ASCII characters
const bytes = Buffer.byteLength(content, "utf-8");
//Add to totals
totalLines += lines;
totalWords += words;
totalBytes += bytes;
formatOutput(lines, words, bytes, path);
}
if (program.args.length > 1) {
formatOutput(totalLines, totalWords, totalBytes, "total");
}