|
1 | | -import { program } from "commander"; |
2 | 1 | import { promises as fs } from "node:fs"; |
| 2 | +import { program } from "commander"; |
3 | 3 |
|
4 | 4 | program |
5 | 5 | .name("cat") |
6 | | - .description("cat sample-files/1.txt ") |
| 6 | + .description("my own cat program") |
7 | 7 | .option("-n", "number all lines") |
8 | | - .argument("<path>", "The file path to process"); |
| 8 | + .option("-b" , "number non-empty lines") |
| 9 | + .argument("<paths...>", "The file path to process"); |
9 | 10 | program.parse(); |
10 | 11 |
|
11 | | -const argv = program.args; |
12 | | -if (argv.length != 1) { |
13 | | - console.error( |
14 | | - `Expected exactly 1 argument (a path) to be passed but got ${argv.length}`, |
15 | | - ); |
| 12 | +const paths = program.args; |
| 13 | +const options = program.opts(); |
| 14 | + |
| 15 | +if (paths.length === 0) { |
| 16 | + console.error("Expected at least one argument (a path)"); |
16 | 17 | process.exit(1); |
17 | 18 | } |
18 | | -const path = argv[0]; |
19 | | -try { |
20 | | - const content = await fs.readFile(path, "utf-8"); |
21 | 19 |
|
22 | | - const addLineNumber = program.opts(); |
23 | | - if (addLineNumber.n) { |
24 | | - const lines = content.split("\n"); |
| 20 | +let lineNumber = 1; |
| 21 | + |
| 22 | +for (const path of paths) { |
| 23 | + try { |
| 24 | + const content = await fs.readFile(path, "utf-8"); |
| 25 | + if(options.b) |
| 26 | + { |
| 27 | + const lines = content.split("\n"); |
| 28 | + |
| 29 | + if (lines[lines.length - 1] === "") { |
| 30 | + lines.pop(); |
| 31 | + } |
| 32 | + for(const line of lines) |
| 33 | + { |
| 34 | + if(line.trim()!=="") |
| 35 | + { |
| 36 | + process.stdout.write(` ${lineNumber} ${line}\n`); |
| 37 | + lineNumber++; |
| 38 | + } |
| 39 | + else {process.stdout.write("\n");} |
| 40 | + } |
25 | 41 |
|
26 | | - if (lines[lines.length - 1] === "") { |
27 | | - lines.pop(); |
28 | 42 | } |
29 | | - |
30 | | - lines.forEach((line, index) => { |
31 | | - process.stdout.write(`${index + 1} ${line}\n`); |
32 | | - }); |
33 | | - } else process.stdout.write(content); |
34 | | -} catch (error) { |
35 | | - console.error(error.message); |
36 | | - process.exit(1); |
| 43 | + else if (options.n) { |
| 44 | + const lines = content.split("\n"); |
| 45 | + |
| 46 | + if (lines[lines.length - 1] === "") { |
| 47 | + lines.pop(); |
| 48 | + } |
| 49 | + |
| 50 | + for (const line of lines) { |
| 51 | + process.stdout.write(` ${lineNumber} ${line}\n`); |
| 52 | + lineNumber++; |
| 53 | + } |
| 54 | + } else { |
| 55 | + process.stdout.write(content); |
| 56 | + } |
| 57 | + } catch (error) { |
| 58 | + console.error(error.message); |
| 59 | + } |
37 | 60 | } |
0 commit comments