Skip to content

Commit b40010c

Browse files
committed
implement cat with -n and -b flags
1 parent 4350f48 commit b40010c

2 files changed

Lines changed: 57 additions & 0 deletions

File tree

implement-shell-tools/cat/cat.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { promises as fs } from "node:fs";
2+
import process from "node:process";
3+
4+
const args = process.argv.slice(2);
5+
6+
if (args.length === 0) {
7+
console.error("Usage: node cat.js [-n] [-b] <file...>");
8+
process.exit(1);
9+
}
10+
const showAllLineNumbers = args.includes("-n");
11+
const showNonBlankNumbers = args.includes("-b");
12+
13+
const filePaths = args.filter((arg) => !arg.startsWith("-"));
14+
15+
let lineNumber = 1;
16+
17+
for (const filePath of filePaths) {
18+
const content = await fs.readFile(filePath, "utf-8");
19+
20+
if (!showAllLineNumbers && !showNonBlankNumbers) {
21+
process.stdout.write(content);
22+
} else {
23+
const lines = content.split("\n");
24+
25+
for (let i = 0; i < lines.length; i++) {
26+
const line = lines[i];
27+
28+
let isLastLine;
29+
if (i === lines.length - 1) {
30+
isLastLine = true;
31+
} else {
32+
isLastLine = false;
33+
}
34+
35+
if (isLastLine && line === "") {
36+
break;
37+
}
38+
39+
if (showAllLineNumbers) {
40+
const paddedNumber = String(lineNumber).padStart(6, " ");
41+
process.stdout.write(`${paddedNumber}\t${line}\n`);
42+
lineNumber++;
43+
} else if (showNonBlankNumbers) {
44+
if (line.trim() === "") {
45+
process.stdout.write("\n");
46+
} else {
47+
const paddedNumber = String(lineNumber).padStart(6, " ");
48+
process.stdout.write(`${paddedNumber}\t${line}\n`);
49+
lineNumber++;
50+
}
51+
}
52+
}
53+
}
54+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"type": "module"
3+
}

0 commit comments

Comments
 (0)