Skip to content

Commit 1ffd705

Browse files
committed
number all lines
1 parent 0edb723 commit 1ffd705

1 file changed

Lines changed: 14 additions & 2 deletions

File tree

implement-shell-tools/cat/cat.mjs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import { program } from "commander";
2-
import { error } from "node:console";
32
import { promises as fs } from "node:fs";
43

54
program
65
.name("cat")
76
.description("cat sample-files/1.txt ")
7+
.option("-n", "number all lines")
88
.argument("<path>", "The file path to process");
99
program.parse();
1010

@@ -18,7 +18,19 @@ if (argv.length != 1) {
1818
const path = argv[0];
1919
try {
2020
const content = await fs.readFile(path, "utf-8");
21-
process.stdout.write(content);
21+
22+
const addLineNumber = program.opts();
23+
if (addLineNumber.n) {
24+
const lines = content.split("\n");
25+
26+
if (lines[lines.length - 1] === "") {
27+
lines.pop();
28+
}
29+
30+
lines.forEach((line, index) => {
31+
process.stdout.write(`${index + 1} ${line}\n`);
32+
});
33+
} else process.stdout.write(content);
2234
} catch (error) {
2335
console.error(error.message);
2436
process.exit(1);

0 commit comments

Comments
 (0)