-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathcat.mjs
More file actions
47 lines (38 loc) · 1.07 KB
/
cat.mjs
File metadata and controls
47 lines (38 loc) · 1.07 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
import { program } from "commander";
import{promises as fs} from "node:fs";
program
.name("cat")
.description("displays the contents of a file")
.option("-n, --number", "Number all output lines")
.option("-b, --number-nonblank", "Number non-blank output lines only")
.argument("<filepaths...>");
program.parse();
const args = program.args;
const opts = program.opts();
if (args.length === 0) {
console.error("Error: Missing <filepath> argument.");
program.help();
}
let globalLineNumber = 1;
for (const path of args) {
try {
const content = await fs.readFile(path, "utf-8");
const lines = content.split('\n');
if (opts.number) {
lines.forEach((line, idx) => {
console.log(`${idx + 1}\t${line}`);
});
} else if (opts.numberNonblank) {
for (const line of lines) {
if (line.trim() !== '') {
console.log(`${globalLineNumber}\t${line}`);
globalLineNumber++;
}
}
} else {
console.log(content);
}
} catch (err) {
console.error(`Error reading file "${path}": ${err.message}`);
}
}