-
-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathcat.js
More file actions
53 lines (46 loc) · 1.64 KB
/
cat.js
File metadata and controls
53 lines (46 loc) · 1.64 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
import { program } from "commander";
import process from "node:process";
import { promises as fs } from "node:fs";
program
.name("cat")
.description("print the content of file")
.option("-n, --line-numbers","Number the output lines, starting at 1")
.option("-b, --number-nonblank", "Number non-empty output lines, overrides -n")
.argument("<paths...>", "The file path(s) to process"); // to support multiple file
program.parse();
const argv = program.args;
const options = program.opts();
if (argv.length === 0) {
console.error(`No file paths provided`);// to support more files
process.exit(1);
}
let lineCounter = 1;
for (const path of argv) {
try {
const content = await fs.readFile(path, "utf-8");
const lines= content.split(/\r?\n/);
if (lines.length && lines[lines.length - 1] === '') {//// Remove trailing empty line if it's just from the final newline
lines.pop();
}
if (options.numberNonblank) {
lines.forEach((line) => {
if (line.trim() === "") {
console.log(""); // Blank line, no number
} else {
const lineNumber = String(lineCounter++).padStart(6, " ");
console.log(`${lineNumber}\t${line}`);
}
});
}else if (options.lineNumbers) {
lines.forEach((line) => {
const lineNumber = String(lineCounter++).padStart(6, ' ');
console.log(`${lineNumber}\t${line}`)
});
} else {
process.stdout.write(content);
if (!content.endsWith('\n')) process.stdout.write('\n');
}
} catch (err) {
console.error(`cat: ${path}: ${err.message}`);
}
}