-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathwc.js
More file actions
54 lines (40 loc) · 1.38 KB
/
wc.js
File metadata and controls
54 lines (40 loc) · 1.38 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
import { program } from "commander";
import { promises as fs } from "node:fs";
program
.option("-l", "Print only the line count")
.option("-w", "Print only the word count")
.option("-c", "Print only the byte count")
.argument("<paths...>", "One or more file paths");
program.parse();
const opts = program.opts();
const paths = program.args;
async function wcFile(path) {
const content = await fs.readFile(path, "utf8");
const lines = content.split("\n").length;
const words = content.trim().split(/\s+/).filter(Boolean).length;
const bytes = Buffer.byteLength(content, "utf8");
return { lines, words, bytes };
}
function formatOutput(counts, filename, opts) {
if (opts.l) return `${counts.lines} ${filename}`;
if (opts.w) return `${counts.words} ${filename}`;
if (opts.c) return `${counts.bytes} ${filename}`;
return `${String(counts.lines).padStart(8)} ${String(counts.words).padStart(
8
)} ${String(counts.bytes).padStart(8)} ${filename}`;
}
async function main() {
let total = { lines: 0, words: 0, bytes: 0 };
let multipleFiles = paths.length > 1;
for (const path of paths) {
const counts = await wcFile(path);
total.lines += counts.lines;
total.words += counts.words;
total.bytes += counts.bytes;
console.log(formatOutput(counts, path, opts));
}
if (multipleFiles) {
console.log(formatOutput(total, "total", opts));
}
}
main();