-
-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathwc.mjs
More file actions
59 lines (49 loc) · 1.51 KB
/
Copy pathwc.mjs
File metadata and controls
59 lines (49 loc) · 1.51 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
import { program } from "commander";
import { promises as fs } from "node:fs";
program
.name("wc")
.description("wc implementation")
.argument("<paths...>", "the file path to process")
.option("-l", "count lines")
.option("-w", "count words")
.option("-c", "count characters");
program.parse();
const paths = program.args;
const options = program.opts();
const noFlag = !options.l && !options.w && !options.c;
const total = {};
let hadError = false;
for (const path of paths) {
try {
const content = await fs.readFile(path, "utf-8");
const linesCounter = content.split("\n").length - 1;
const trimmedContent = content.trim();
const wordsCounter =
trimmedContent === "" ? 0 : trimmedContent.split(/\s+/).length;
const characterCounter = content.length;
const results = [];
if (options.l || noFlag) {
results.push(linesCounter);
total["lineCounter"] = (total["lineCounter"] ?? 0) + linesCounter;
}
if (options.w || noFlag) {
results.push(wordsCounter);
total["wordsCounter"] = (total["wordsCounter"] ?? 0) + wordsCounter;
}
if (options.c || noFlag) {
results.push(characterCounter);
total["characterCounter"] =
(total["characterCounter"] ?? 0) + characterCounter;
}
console.log(results.join(" ") + " " + path);
} catch (error) {
console.error(error.message);
hadError = true;
}
}
if (paths.length > 1) {
console.log(Object.values(total).join(" "),"total")
}
if (hadError) {
process.exitCode = 1;
}