-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathwc.js
More file actions
65 lines (57 loc) · 1.65 KB
/
wc.js
File metadata and controls
65 lines (57 loc) · 1.65 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
import { program } from "commander";
import * as fs from "node:fs/promises";
program
.name("wc")
.description("word, line and byte count")
.argument("<paths...>", "The file path(s) to process.")
.option(
"-l, --lines",
"The number of lines in each input file is written to the standard output.",
)
.option(
"-w, --words",
"The number of words in each input file is written to the standard output.",
)
.option(
"-c --bytes",
"The number of bytes in each input file is written to the standard output.",
);
program.parse();
try {
const filePaths = program.args;
const results = {};
for (const filePath of filePaths) {
const file = await fs.open(filePath);
const stats = await fs.stat(filePath);
const count = { lines: 0, words: 0, bytes: stats.size };
try {
for await (const line of file.readLines()) {
count.lines++;
const trimmed = line.trim();
if (trimmed.length > 0) {
count.words += trimmed.split(/\s+/).length;
}
}
} finally {
await file.close();
}
results[filePath] = count;
}
if (filePaths.length > 1) {
const total = { lines: 0, words: 0, bytes: 0 };
for (const file of Object.values(results)) {
total.lines += file.lines;
total.words += file.words;
total.bytes += file.bytes;
}
results["total"] = total;
}
const options = program.opts();
const noOptionsProvided = !Object.keys(options).length;
const selectedOptionKeys = [...Object.keys(options)];
noOptionsProvided
? console.table(results)
: console.table(results, selectedOptionKeys);
} catch (err) {
console.error(err.message);
}