Skip to content

Commit b6e54aa

Browse files
committed
Implement cat command
1 parent e328bd5 commit b6e54aa

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

implement-shell-tools/Package.json

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

implement-shell-tools/cat/cat.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { program } from "commander";
2+
import { promises as fs } from "node:fs";
3+
import process from "node:process";
4+
5+
program
6+
.name("cat command")
7+
.description("Implementing 'cat' command")
8+
.option("-n", "The line numbers")
9+
.option("-b", "The line numbers only for non-empty lines")
10+
.argument("<paths...>", "The file paths to process");
11+
12+
program.parse();
13+
14+
const paths = program.args;
15+
let lineNumber = 1;
16+
const displayLineNumber = program.opts().n;
17+
const displayNonEmptyLineNumber = program.opts().b;
18+
19+
for(const path of paths){
20+
const content = await fs.readFile(path, "utf-8");
21+
const lines = content.split("\n");
22+
for(const line of lines){
23+
if(displayLineNumber){
24+
console.log(`${String(lineNumber).padStart(6, ' ')} ${line}`);
25+
lineNumber++;
26+
} else if (displayNonEmptyLineNumber) {
27+
if (line.trim()) {
28+
console.log(`${String(lineNumber).padStart(6, ' ')} ${line}`);
29+
lineNumber++;
30+
} else {
31+
console.log(line);
32+
33+
}
34+
}
35+
}
36+
}

implement-shell-tools/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.

0 commit comments

Comments
 (0)