Skip to content

Commit e2983ea

Browse files
committed
Implement cat CLI with -n and -b options
1 parent a49c91e commit e2983ea

3 files changed

Lines changed: 76 additions & 0 deletions

File tree

implement-shell-tools/cat/cat.mjs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { promises as fs } from "node:fs";
2+
import { program } from "commander";
3+
4+
program
5+
.name("cat")
6+
.description("my own cat program")
7+
.option("-n", "number all lines")
8+
.option("-b", "number non-empty lines")
9+
.argument("<paths...>", "The file path to process");
10+
program.parse();
11+
12+
const paths = program.args;
13+
const options = program.opts();
14+
15+
let lineNumber = 1;
16+
17+
for (const path of paths) {
18+
try {
19+
const content = await fs.readFile(path, "utf-8");
20+
if (options.b) {
21+
const lines = content.split("\n");
22+
23+
if (lines[lines.length - 1] === "") {
24+
lines.pop();
25+
}
26+
for (const line of lines) {
27+
if (line.trim() !== "") {
28+
process.stdout.write(` ${lineNumber} ${line}\n`);
29+
lineNumber++;
30+
} else {
31+
process.stdout.write("\n");
32+
}
33+
}
34+
} else if (options.n) {
35+
const lines = content.split("\n");
36+
37+
if (lines[lines.length - 1] === "") {
38+
lines.pop();
39+
}
40+
41+
for (const line of lines) {
42+
process.stdout.write(` ${lineNumber} ${line}\n`);
43+
lineNumber++;
44+
}
45+
} else {
46+
process.stdout.write(content);
47+
}
48+
} catch (error) {
49+
console.error(error.message);
50+
}
51+
}

implement-shell-tools/package-lock.json

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

implement-shell-tools/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": "^15.0.0"
4+
}
5+
}

0 commit comments

Comments
 (0)