-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathscript-cat.js
More file actions
executable file
·65 lines (53 loc) · 1.43 KB
/
script-cat.js
File metadata and controls
executable file
·65 lines (53 loc) · 1.43 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/env node
import { program } from "commander";
import { promises as fs } from "node:fs";
// Setup CLI
program
.name("cat")
.description("Concatenate files and print on the standard output")
.option("-n, --number", "number all output lines")
.option("-b, --number-nonblank", "number nonempty output lines")
.argument("<path...>", "file(s) to read");
program.parse();
const files = program.args;
const { number, numberNonblank } = program.opts();
// Validate input
if (files.length === 0) {
console.error("cat: missing file operand");
process.exit(1);
}
let lineNumber = 1;
// Helper to print lines with optional numbering
function printLine(line, shouldNumber) {
if (shouldNumber) {
console.log(`${String(lineNumber).padStart(6)}\t${line}`);
lineNumber++;
} else {
console.log(line);
}
}
for (const file of files) {
let content;
try {
content = await fs.readFile(file, "utf8");
} catch (err) {
console.error(`cat: ${file}: ${err.message}`);
continue;
}
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Avoid printing an extra line if file ends with \n
if (i === lines.length - 1 && line === "") {
break;
}
const isBlank = line.trim() === "";
if (numberNonblank) {
printLine(line, !isBlank);
} else if (number) {
printLine(line, true);
} else {
printLine(line, false);
}
}
}