-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathcat.js
More file actions
38 lines (31 loc) · 973 Bytes
/
cat.js
File metadata and controls
38 lines (31 loc) · 973 Bytes
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
import { program } from "commander";
import process from "node:process";
import { promises as fs } from "node:fs";
let showNumber = false;
program
.name("cat")
.description("Prints the output of a file to the console")
.option("-n, --number", "Displays the lines along with their number")
.argument("<path>", "The file path")
.allowExcessArguments();
program.parse();
const argv = program.args;
if (argv.length < 1) {
console.error(
`Expected exactly 1 or more arguments (paths) to be passed but got ${argv.length}.`,
);
process.exit(1);
}
showNumber = program.opts().number;
const stringArr = [];
for (const path of argv) {
stringArr.push(await fs.readFile(path, "utf-8"));
}
const flatArr = stringArr.flatMap((l) =>
l
.split("\n")
.map((l, i, a) => (i < a.length - 1 ? l + "\n" : l))
.filter((l) => l !== ""),
);
if (!showNumber) console.log(flatArr.join(""));
else console.log(flatArr.map((l, i) => `${i + 1} ${l}`).join(""));