-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathwc.js
More file actions
61 lines (51 loc) · 1.33 KB
/
wc.js
File metadata and controls
61 lines (51 loc) · 1.33 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
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
function countFile(filePath, options) {
try {
const data = fs.readFileSync(filePath, 'utf8');
const lines = data.split('\n').length;
const words = data.split(/\s+/).filter(Boolean).length;
const bytes = Buffer.byteLength(data, 'utf8');
if (options.lines) {
console.log(`${lines}\t${filePath}`);
} else if (options.words) {
console.log(`${words}\t${filePath}`);
} else if (options.bytes) {
console.log(`${bytes}\t${filePath}`);
} else {
console.log(`${lines}\t${words}\t${bytes}\t${filePath}`);
}
} catch (err) {
console.error(`wc: ${filePath}: No such file or directory`);
}
}
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) => {
const filePath = path.resolve(file);
countFile(filePath, options);
});
}
main();