-
-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathcat.js
More file actions
65 lines (55 loc) · 1.64 KB
/
Copy pathcat.js
File metadata and controls
65 lines (55 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
54
55
56
57
58
59
60
61
62
63
64
65
import { readFileSync } from "node:fs";
import process from "node:process";
// Note: takes only one flag, -n or -b, and accepts whatever the last flag is
// can parse flag from any position in args
// capturing the user args
const args = process.argv.slice(2);
let flag;
const paths = [];
// the * (glob expansion is done automatically by zsh, bash etc. on linux)
for (const arg of args) {
if (arg === "-n" || arg === "-b") {
flag = arg;
} else {
paths.push(arg);
}
}
// if no file is supplied exit with error
if (paths.length === 0) {
console.error("usage: cat [-n] <file...>");
process.exit(1);
}
// starting file number, if lines need to be prepended
for (const path of paths) {
let lineNum = 1;
let file;
try {
// using sync as it's a simple short program
file = readFileSync(path, "utf-8");
} catch (err) {
console.error(`cat: ${path}: ${err.message}`);
continue; // Real cat continues to next file if current file not found
}
const lines = file.split("\n");
// remove trailing empty line as this how real cat works
if (lines[lines.length - 1] === "") lines.pop();
if (flag === "-n") {
for (const line of lines) {
console.log(`${lineNum} ${line}`);
lineNum++;
}
} else if (flag === "-b") {
for (const line of lines) {
if (line === "") {
console.log(line);
} else {
console.log(`${lineNum} ${line}`);
lineNum++;
}
}
} else {
for (const line of lines) {
console.log(line);
}
}
}