-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathcat.mjs
More file actions
60 lines (51 loc) · 1.3 KB
/
cat.mjs
File metadata and controls
60 lines (51 loc) · 1.3 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("my own cat program")
.option("-n", "number all lines")
.option("-b" , "number non-empty lines")
.argument("<paths...>", "The file path to process");
program.parse();
const paths = program.args;
const options = program.opts();
if (paths.length === 0) {
console.error("Expected at least one argument (a path)");
process.exit(1);
}
let lineNumber = 1;
for (const path of paths) {
try {
const content = await fs.readFile(path, "utf-8");
if(options.b)
{
const lines = content.split("\n");
if (lines[lines.length - 1] === "") {
lines.pop();
}
for(const line of lines)
{
if(line.trim()!=="")
{
process.stdout.write(` ${lineNumber} ${line}\n`);
lineNumber++;
}
else {process.stdout.write("\n");}
}
}
else if (options.n) {
const lines = content.split("\n");
if (lines[lines.length - 1] === "") {
lines.pop();
}
for (const line of lines) {
process.stdout.write(` ${lineNumber} ${line}\n`);
lineNumber++;
}
} else {
process.stdout.write(content);
}
} catch (error) {
console.error(error.message);
}
}