-
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathcat.mjs
More file actions
51 lines (43 loc) · 1.29 KB
/
Copy pathcat.mjs
File metadata and controls
51 lines (43 loc) · 1.29 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
import { program } from "commander";
import {promises as fs} from "node:fs";
program
.name("cat")
.description("read, display, and concatenate text files.")
.option("-n", " Number all output lines.")
.option("-b", " Number non-blank output lines.")
.arguments("<paths...>"); // allow more file paths
program.parse();
const options = program.opts();
const paths = program.args;
const numNonBlank = options.b;
const numAll = !!options.n && !numNonBlank;
let hadError = false;
for(const path of paths){
let content;
try {
content = await fs.readFile(path, "utf-8")
} catch(err) {
console.error(`Error reading file "${path}": ${err.message} `);
hadError = true;
continue;
}
// split file into lines
let lines = content.replace(/\n$/, "").split("\n");
let lineNum = 1;
for (const line of lines){
if(numNonBlank){
if(line.trim() !== ""){
console.log(`${lineNum.toString().padStart(5)} ${line}`)
lineNum++;
} else {
console.log("");
}
} else if(numAll){
console.log(`${lineNum.toString().padStart(5)} ${line}`)
lineNum++;
} else{
console.log(`${line}`)
}
}
}
if (hadError) process.exit(1);