Skip to content

Commit 8020365

Browse files
committed
implement cat
1 parent 0482554 commit 8020365

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

implement-shell-tools/cat/cat.mjs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { program } from "commander";
2+
import {promises as fs} from "node:fs";
3+
4+
program
5+
.name("cat")
6+
.description("read, display, and concatenate text files.")
7+
.option("-n", " Number all output lines.")
8+
.option("-b", " Number non-blank output lines.")
9+
.arguments("<paths...>"); // allow more file paths
10+
11+
program.parse();
12+
13+
const options = program.opts();
14+
const paths = program.args;
15+
16+
for(const path of paths){
17+
let content;
18+
try {
19+
content = await fs.readFile(path, "utf-8")
20+
} catch(err) {
21+
console.error(`Error reading file "${path}": ${err.message} `);
22+
continue;
23+
}
24+
25+
// split file into lines
26+
let lines = content.replace(/\n$/, "").split("\n");
27+
28+
let lineNum = 1;
29+
30+
for (const line of lines){
31+
if(options.b){
32+
if(line.trim() !== ""){
33+
console.log(`${lineNum.toString().padStart(5)} ${line}`)
34+
lineNum++;
35+
} else {
36+
console.log("");
37+
}
38+
} else if(options.n){
39+
console.log(`${lineNum.toString().padStart(5)} ${line}`)
40+
lineNum++;
41+
} else{
42+
console.log(`${line}`)
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)