|
1 | 1 | #!/usr/bin/env node |
2 | 2 |
|
3 | 3 | const fs = require('fs'); |
4 | | -const path = require('path'); |
5 | 4 |
|
6 | | -function countFile(filePath, options) { |
| 5 | +function countFile(file, options) { |
7 | 6 | try { |
8 | | - const data = fs.readFileSync(filePath, 'utf8'); |
| 7 | + const data = fs.readFileSync(file, 'utf8'); |
9 | 8 |
|
10 | 9 | const lines = data.split('\n').length; |
11 | 10 | const words = data.split(/\s+/).filter(Boolean).length; |
12 | 11 | const bytes = Buffer.byteLength(data, 'utf8'); |
13 | 12 |
|
14 | | - if (options.lines) { |
15 | | - console.log(`${lines}\t${filePath}`); |
16 | | - } else if (options.words) { |
17 | | - console.log(`${words}\t${filePath}`); |
18 | | - } else if (options.bytes) { |
19 | | - console.log(`${bytes}\t${filePath}`); |
20 | | - } else { |
21 | | - console.log(`${lines}\t${words}\t${bytes}\t${filePath}`); |
22 | | - } |
| 13 | + const results = []; |
| 14 | + if (options.lines) results.push(lines); |
| 15 | + if (options.words) results.push(words); |
| 16 | + if (options.bytes) results.push(bytes); |
| 17 | + |
| 18 | + console.log(`${results.join('\t')}\t${file}`); |
23 | 19 | } catch (err) { |
24 | | - console.error(`wc: ${filePath}: No such file or directory`); |
| 20 | + console.error(`wc: ${file}: ${err.code === 'ENOENT' ? 'No such file or directory' : 'An error occurred'}`); |
| 21 | + process.exit(1); |
25 | 22 | } |
26 | 23 | } |
27 | 24 |
|
@@ -53,8 +50,7 @@ function main() { |
53 | 50 | } |
54 | 51 |
|
55 | 52 | files.forEach((file) => { |
56 | | - const filePath = path.resolve(file); |
57 | | - countFile(filePath, options); |
| 53 | + countFile(file, options); |
58 | 54 | }); |
59 | 55 | } |
60 | 56 |
|
|
0 commit comments