-
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathwc.mjs
More file actions
69 lines (56 loc) · 1.69 KB
/
Copy pathwc.mjs
File metadata and controls
69 lines (56 loc) · 1.69 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
import { program } from "commander";
import { promises as fs } from "node:fs";
program
.name("wc")
.description("Display numbers of line, words, and bytes in each file")
.option("-l", "Number of lines")
.option("-w", "Number of words")
.option("-c", "Number of bytes")
.argument("<path...>");
program.parse();
const options = program.opts();
const paths = program.args;
let totalLines = 0;
let totalWords = 0;
let totalBytes = 0;
let hadError = false;
for(const path of paths){
let content;
try{
content = await fs.readFile(path, "utf-8");
} catch (err){
console.error(`Error reading file "${path}":`, err.message);
hadError = true;
continue;
}
const lines = content.replace(/\n$/, "").split("\n");
const words = content.trim().split(/\s+/); // handles multiple spaces
const { size } = await fs.stat(path);
const lineCount = lines.length;
const wordCount = words.length;
const byteCount = size;
totalLines += lineCount;
totalWords += wordCount;
totalBytes += byteCount;
if(options.l) {
console.log(`\t${lineCount} ${path}`);
} else if(options.w) {
console.log(`\t${wordCount} ${path}`);
} else if(options.c) {
console.log(`\t${byteCount} ${path}`)
} else {
console.log(`\t${lineCount}\t${wordCount}\t${size} ${path}`);
}
}
if (paths.length > 1) {
if (options.l) {
console.log(`\t${totalLines} total`);
} else if (options.w) {
console.log(`\t${totalWords} total`);
} else if (options.c) {
console.log(`\t${totalBytes} total`);
} else {
console.log(`\t${totalLines}\t${totalWords}\t${totalBytes} total`);
}
}
if (hadError) process.exit(1);