-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathcat.js
More file actions
53 lines (48 loc) · 1.59 KB
/
cat.js
File metadata and controls
53 lines (48 loc) · 1.59 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 process from "node:process";
import { promises as fs } from "node:fs";
import { program } from "commander";
program
.option("-n, --number", "number all output lines")
.option("-b, --number-nonblank", "number only non-empty lines")
.arguments("<files...>")
.parse();
const cliOptions = program.opts();
const filePathsToRead = program.args;
async function readAndOutputFiles() {
try {
const fileContents = await Promise.all(
filePathsToRead.map((filePath) => fs.readFile(filePath, "utf-8")),
);
const concatenatedContent = fileContents.join("");
if (cliOptions.number) {
// apply -n logic: number all lines
const contentLines = concatenatedContent.split("\n");
const numberedOutput = contentLines
.map((line, index) => {
return `${String(index + 1).padStart(6)} ${line}`;
})
.join("\n");
process.stdout.write(numberedOutput);
} else if (cliOptions.numberNonblank) {
// apply -b logic: number only non-empty lines
const contentLines = concatenatedContent.split("\n");
let nonblankLineNumber = 0;
const numberedOutput = contentLines
.map((line) => {
if (line.trim() === "") {
return line;
}
nonblankLineNumber++;
return `${String(nonblankLineNumber).padStart(6)} ${line}`;
})
.join("\n");
process.stdout.write(numberedOutput);
} else {
process.stdout.write(concatenatedContent);
}
} catch (err) {
console.error("Error reading multiple files:", err);
process.exitCode = 1;
}
}
readAndOutputFiles();