-
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathcat.js
More file actions
43 lines (32 loc) · 1.01 KB
/
Copy pathcat.js
File metadata and controls
43 lines (32 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { program } from "commander";
import { promises as fs } from "node:fs";
program
.name("cat")
.description("Prints file content with optional line numbers")
.argument("<file>", "file to read")
.option("-n, --number", "number all lines")
.option("-b, --number-nonblank", "number non-blank lines only")
.parse();
const options = program.opts();
const filePath = program.args[0];
try {
const content = await fs.readFile(filePath, "utf-8");
const lines = content.split("\n");
lines.forEach((line, index) => {
const lineNumber = index + 1;
if (options.number) {
console.log(`${lineNumber.toString().padStart(4)} ${line}`);
} else if (options.numberNonblank) {
if (line.trim() === "") {
console.log(" " + line);
} else {
console.log(`${lineNumber.toString().padStart(4)} ${line}`);
}
} else {
console.log(line);
}
});
} catch (err) {
console.error(`Error reading file "${filePath}":`, err.message);
process.exit(1);
}