-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathwc.js
More file actions
57 lines (46 loc) · 1.22 KB
/
wc.js
File metadata and controls
57 lines (46 loc) · 1.22 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
#!/usr/bin/env node
const fs = require('fs');
function countFile(file, options) {
try {
const data = fs.readFileSync(file, 'utf8');
const lines = data.split('\n').length;
const words = data.split(/\s+/).filter(Boolean).length;
const bytes = Buffer.byteLength(data, 'utf8');
const results = [];
if (options.lines) results.push(lines);
if (options.words) results.push(words);
if (options.bytes) results.push(bytes);
console.log(`${results.join('\t')}\t${file}`);
} catch (err) {
console.error(`wc: ${file}: ${err.code === 'ENOENT' ? 'No such file or directory' : 'An error occurred'}`);
process.exit(1);
}
}
function main() {
const args = process.argv.slice(2);
const options = {
lines: false,
words: false,
bytes: false,
};
const files = [];
args.forEach((arg) => {
if (arg === '-l') {
options.lines = true;
} else if (arg === '-w') {
options.words = true;
} else if (arg === '-c') {
options.bytes = true;
} else {
files.push(arg);
}
});
if (files.length === 0) {
console.error('Usage: wc [-l | -w | -c] <file>...');
process.exit(1);
}
files.forEach((file) => {
countFile(file, options);
});
}
main();