-
-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathwc.js
More file actions
75 lines (65 loc) · 2.17 KB
/
Copy pathwc.js
File metadata and controls
75 lines (65 loc) · 2.17 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
67
68
69
70
71
72
73
74
75
import { program } from "commander";
import fs, { chownSync } from "node:fs";
import process from "node:process";
program
.name("wc")
.description("Mimics the wc command line tool")
.option("-w")
.option("-c")
.option("-l")
.argument("<files...>", "files to process");
program.parse();
const options = program.opts();
const paths = program.args;
// if no -lwc flags are supplied, wc prints
// lines, words, bytes of each file
// whereas if any flags are supplied only those
// values are printed
if (Object.keys(options).length === 0) {
options.l = options.w = options.c = true;
}
// keeps track of total values for each of the data
// incrementally updated in the loop below
const totals = { l: 0, w: 0, c: 0 };
let fileCount = 0;
for (const path of paths) {
if (fs.statSync(path).isDirectory()) {
console.log(`wc: ${path}: read: Is a directory`);
} else {
fileCount++;
let outputStr = "";
const file = fs.readFileSync(path, "utf-8");
if (options.l) {
const lines = file.split("\n");
// exclude trailing empty line from count
if (lines.at(-1) === "") {
lines.pop();
}
const lineCount = lines.length;
totals.l += lineCount;
outputStr += `\t${lineCount}`;
}
if (options.w) {
// real wc splits not just on " ", but on white spaces more generally
const words = file.split(/\s+/).filter(Boolean);
const wordCount = words.length;
totals.w += wordCount;
outputStr += `\t${wordCount}`;
}
if (options.c) {
file.size;
const byteCount = fs.statSync(path).size;
totals.c += byteCount;
outputStr += `\t${byteCount}`;
}
outputStr += ` ${path}`;
console.log(outputStr);
}
}
// if there's more than one file, print out a total
// if a flag is not selected, then the value for that flag is 0
// filter out anything with a total of 0
if (fileCount > 1) {
const totalsArr = Object.values(totals).filter((elem) => elem !== 0);
console.log(`\t${totalsArr.join("\t")} total`);
}