generated from CodeYourFuture/Module-Template
-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcat.js
47 lines (42 loc) · 1.29 KB
/
cat.js
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
const { promises: fs } = require("fs");
const process = require("process");
const { program } = require("commander");
program
.name("cat")
.description("Implement a version of the cat program")
.option("-n, --number", "Number the output lines, starting at 1")
.option("-b, --number2", "Number the nonempty lines, starting at 1")
.argument("<paths...>", "The file paths to process")
.parse(process.argv);
let args = program.args;
//const nOption = program.opts().number;
//const bOption = program.opts().number2;
const { number: nOption, number2: bOption } = program.opts();
let lineNumber = 1;
let nonEmptyLineNumber = 1;
function printLinesWithOptions(lines) {
lines.forEach((line, index) => {
if (nOption) {
console.log(`${lineNumber++} ${line}`);
} else if (bOption && line.trim()) {
console.log(`${nonEmptyLineNumber++} ${line}`);
} else {
console.log(line);
}
});
}
async function readFileContent(path) {
try {
const content = await fs.readFile(path, { encoding: "utf-8" });
const lines = content.split("\n");
if(lines[lines.length - 1] === "") {
lines.pop();
}
printLinesWithOptions(lines);
} catch (err) {
console.error(`Error reading file ${path}: ${err.message}`);
}
}
args.forEach((arg) => {
readFileContent(arg);
});