-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathcat.js
More file actions
42 lines (34 loc) · 1.05 KB
/
cat.js
File metadata and controls
42 lines (34 loc) · 1.05 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
import { program } from "commander";
import { promises as fs } from "node:fs";
import process from "node:process";
program
.name("display-file-content")
.description("Implement cat command with -n and -b flag support")
.option("-n, --number-all-lines", "Number every line in the file")
.option("-b, --number-non-empty-lines", "Number non empty lines in the file")
.argument("<paths...>", "File paths to process");
program.parse(process.argv);
const filepaths = program.args;
const options = program.opts();
let lineNumber = 1;
for (const filepath of filepaths) {
const fileContent = await fs.readFile(filepath, "utf8");
const lines = fileContent.split("\n");
for (const line of lines) {
if (options.numberAllLines) {
console.log(`${lineNumber} ${line}`);
lineNumber++;
continue;
}
if (options.numberNonEmptyLines) {
if (line.trim() === "") {
console.log(line);
} else {
console.log(`${lineNumber} ${line}`);
lineNumber++;
}
continue;
}
console.log(line);
}
}