Skip to content

Commit 7036a76

Browse files
committed
feat: add -n and -b flags in cat implemention
1 parent 1ffd705 commit 7036a76

1 file changed

Lines changed: 47 additions & 24 deletions

File tree

implement-shell-tools/cat/cat.mjs

Lines changed: 47 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,60 @@
1-
import { program } from "commander";
21
import { promises as fs } from "node:fs";
2+
import { program } from "commander";
33

44
program
55
.name("cat")
6-
.description("cat sample-files/1.txt ")
6+
.description("my own cat program")
77
.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");
910
program.parse();
1011

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)");
1617
process.exit(1);
1718
}
18-
const path = argv[0];
19-
try {
20-
const content = await fs.readFile(path, "utf-8");
2119

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+
}
2541

26-
if (lines[lines.length - 1] === "") {
27-
lines.pop();
2842
}
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+
}
3760
}

0 commit comments

Comments
 (0)