Skip to content

Commit eb634c5

Browse files
committed
cat-implementation
1 parent 896a7ff commit eb634c5

6 files changed

Lines changed: 69 additions & 0 deletions

File tree

.DS_Store

6 KB
Binary file not shown.

implement-shell-tools/.DS_Store

6 KB
Binary file not shown.
6 KB
Binary file not shown.
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { program } from "commander";
2+
import { promises as fs } from "node:fs";
3+
4+
5+
program
6+
.name("cat")
7+
.description("Prints file content with optional line numbers")
8+
.argument("<file>", "file to read")
9+
.option("-n, --number", "number all lines")
10+
.option("-b, --number-nonblank", "number non-blank lines only")
11+
.parse();
12+
13+
const options = program.opts();
14+
const filePath = program.args[0];
15+
16+
try {
17+
const content = await fs.readFile(filePath, "utf-8");
18+
const lines = content.split("\n");
19+
20+
lines.forEach((line, index) => {
21+
const lineNumber = index + 1;
22+
if (options.number) {
23+
24+
console.log(`${lineNumber.toString().padStart(4)} ${line}`);
25+
} else if (options.numberNonblank) {
26+
27+
if (line.trim() === "") {
28+
console.log(" " + line);
29+
} else {
30+
console.log(`${lineNumber.toString().padStart(4)} ${line}`);
31+
}
32+
} else {
33+
34+
console.log(line);
35+
}
36+
});
37+
} catch (err) {
38+
console.error(`Error reading file "${filePath}":`, err.message);
39+
process.exit(1);
40+
}
41+
42+
43+

package-lock.json

Lines changed: 21 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"dependencies": {
3+
"commander": "^14.0.0"
4+
}
5+
}

0 commit comments

Comments
 (0)