Skip to content

Commit 276fc2b

Browse files
committed
implementing a logic that behive as cat command
1 parent 4350f48 commit 276fc2b

File tree

1 file changed

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

1 file changed

+40
-0
lines changed

implement-shell-tools/cat/cat.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import process from "node:process";
2+
import { promises as fs } from "node:fs";
3+
4+
// THis will give an array without the path to node and to the file.
5+
const argv = process.argv.slice(2);
6+
7+
//Get line numbers.
8+
const showNumbers = argv.includes("-n");
9+
const showNonBlankNumbers = argv.includes("-b");
10+
11+
//filter the - from the array argv as it's a flag.
12+
const filePaths = argv.filter((arg) => !arg.startsWith("-"));
13+
let counterLines = 1;
14+
15+
for (const path of filePaths) {
16+
try {
17+
const content = await fs.readFile(path, "utf-8");
18+
19+
//split the text at the new line character.
20+
const splitLines = content.split("\n");
21+
22+
splitLines.forEach((line) => {
23+
if (showNumbers) {
24+
console.log(`${counterLines++} ${line}`);
25+
} else if (showNonBlankNumbers) {
26+
// increment and show numbers only if the line is not empty.
27+
if (line.trim() !== "") {
28+
console.log(`${counterLines++} ${line}`);
29+
} else {
30+
// print empty lines
31+
console.log(line);
32+
}
33+
} else {
34+
console.log(line);
35+
}
36+
});
37+
} catch (error) {
38+
console.log(`Could not read: ${path}`);
39+
}
40+
}

0 commit comments

Comments
 (0)