-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcat.js
More file actions
60 lines (51 loc) · 1.22 KB
/
cat.js
File metadata and controls
60 lines (51 loc) · 1.22 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
import { promises as fs } from "node:fs";
import { program } from "commander";
program
.name("cat")
.description("Concatenate and print files")
.option("-n", "Number the output lines, starting at 1")
.option("-b", "Number the non-blank output lines, starting at 1")
.argument("<sample-files...>", "The file path to process")
.parse();
const argv = program.args;
const opts = program.opts();
const countLines = (data) => {
const lines = data.split("\n");
if (lines[lines.length - 1] === "") {
lines.pop();
}
let lineNum = 1;
for (const line of lines) {
if (opts.b) {
if (line.trim() === "") {
console.log();
} else {
console.log(`${lineNum} ${line}`);
lineNum++;
}
} else if (opts.n) {
console.log(`${lineNum} ${line}`);
lineNum++;
}
}
};
async function example(path) {
try {
const data = await fs.readFile(path, { encoding: "utf8" });
if (opts["b"]) {
countLines(data);
} else if (opts["n"]) {
countLines(data);
} else {
console.log(data.trimEnd());
}
} catch (err) {
console.error(err);
}
}
const handleInput = async () => {
for (const path of argv) {
await example(path);
}
};
handleInput();