Skip to content

Commit 8cd986e

Browse files
authored
Implement cat command to concatenate files
1 parent b5089a2 commit 8cd986e

File tree

1 file changed

+60
-0
lines changed
  • implement-shell-tools/cat

1 file changed

+60
-0
lines changed

implement-shell-tools/cat/cat.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import { promises as fs } from "node:fs";
2+
import { program } from "commander";
3+
4+
program
5+
.name("cat")
6+
.description("Concatenate and print files")
7+
.option("-n", "Number the output lines, starting at 1")
8+
.option("-b", "Number the non-blank output lines, starting at 1")
9+
.argument("<sample-files...>", "The file path to process")
10+
.parse();
11+
12+
const argv = program.args;
13+
14+
const opts = program.opts();
15+
16+
const countLines = (data) => {
17+
const lines = data.split("\n");
18+
if (lines[lines.length - 1] === "") {
19+
lines.pop();
20+
}
21+
22+
let lineNum = 1;
23+
24+
for (const line of lines) {
25+
if (opts.b) {
26+
if (line.trim() === "") {
27+
console.log();
28+
} else {
29+
console.log(`${lineNum} ${line}`);
30+
lineNum++;
31+
}
32+
} else if (opts.n) {
33+
console.log(`${lineNum} ${line}`);
34+
lineNum++;
35+
}
36+
}
37+
};
38+
39+
async function example(path) {
40+
try {
41+
const data = await fs.readFile(path, { encoding: "utf8" });
42+
if (opts["b"]) {
43+
countLines(data);
44+
} else if (opts["n"]) {
45+
countLines(data);
46+
} else {
47+
console.log(data.trimEnd());
48+
}
49+
} catch (err) {
50+
console.error(err);
51+
}
52+
}
53+
54+
const handleInput = async () => {
55+
for (const path of argv) {
56+
await example(path);
57+
}
58+
};
59+
60+
handleInput();

0 commit comments

Comments
 (0)