-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathwc.js
More file actions
90 lines (75 loc) · 2.69 KB
/
wc.js
File metadata and controls
90 lines (75 loc) · 2.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { program } from "commander";
import { promises as fs } from "node:fs";
import process from "node:process";
import { stat } from "node:fs/promises";
program
.name("count-containing-lines-words-characters")
.description("Counts lines, words or characters in a file (or all files) inside a directory")
.option("-l, --line", "The number of lines in each file")
.option("-w, --word", "The number of words in each file")
.option("-c, --character", "The number of characters in each file")
.argument("<path...>", "The file path to process");
program.parse();
const argv = program.args;
const options = program.opts();
function counter(item) {
const lines = item.trim().split("\n").length;
const words = item.split(/\s+/).filter(Boolean).length;
const characters = item.length;
return { lines, words, characters };
}
let totalLines = 0;
let totalWords = 0;
let totalCharacters = 0;
let fileCount = 0;
for (const path of argv) {
const pathInfo = await stat(path);
if (pathInfo.isFile()) {
const content = await fs.readFile(path, "utf-8");
const stats = counter(content);
if (options.line) {
console.log(`${stats.lines} ${path}`);
} else if (options.word) {
console.log(`${stats.words} ${path}`);
} else if (options.character) {
console.log(`${stats.characters} ${path}`);
} else {
console.log(`${stats.lines} ${stats.words} ${stats.characters} ${path}`);
}
totalLines += stats.lines;
totalWords += stats.words;
totalCharacters += stats.characters;
fileCount++;
} else if (pathInfo.isDirectory()) {
const files = await fs.readdir(path);
for (const file of files) {
const filePath = `${path}/${file}`;
const fileContent = await fs.readFile(filePath, "utf-8");
const stats = counter(fileContent);
if (options.line) {
console.log(`${stats.lines} ${filePath}`);
} else if (options.word) {
console.log(`${stats.words} ${filePath}`);
} else if (options.character) {
console.log(`${stats.characters} ${filePath}`);
} else {
console.log(`${stats.lines} ${stats.words} ${stats.characters} ${filePath}`);
}
totalLines += stats.lines;
totalWords += stats.words;
totalCharacters += stats.characters;
fileCount++;
}
}
}
if (fileCount > 1) {
if (options.line) {
console.log(`${totalLines} total`);
} else if (options.word) {
console.log(`${totalWords} total`);
} else if (options.character) {
console.log(`${totalCharacters} total`);
} else {
console.log(`${totalLines} ${totalWords} ${totalCharacters} total`);
}
}