-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathmyCat.js
More file actions
executable file
·76 lines (61 loc) · 1.69 KB
/
myCat.js
File metadata and controls
executable file
·76 lines (61 loc) · 1.69 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
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/env node
const { program } = require("commander");
const fs = require("fs");
const path = require("path");
function expandWildcard(pattern) {
const dir = path.dirname(pattern);
const base = path.basename(pattern);
if (!base.includes("*")) return [pattern];
let files;
try {
files = fs.readdirSync(dir);
} catch {
console.error(`cat: ${pattern}: No such directory`);
return [];
}
const regex = new RegExp("^" + base.replace(/\*/g, ".*") + "$");
return files
.filter((f) => regex.test(f))
.map((f) => path.join(dir, f));
}
function printFile(filename, options) {
let text;
try {
text = fs.readFileSync(filename, "utf-8");
} catch {
console.error(`cat: ${filename}: No such file`);
return;
}
const lines = text.split("\n");
if (lines[lines.length - 1] === "") lines.pop();
let counter = 1;
const paddingSize = 6;
lines.forEach((line) => {
const isEmpty = line.trim() === "";
const shouldNumber =
options.numberAll ||
(options.numberNonempty && !isEmpty);
if (shouldNumber) {
console.log(
`${String(counter).padStart(paddingSize)} ${line}`
);
counter++;
} else {
console.log(line);
}
});
}
program
.name("mycat")
.description("A custom implementation of the cat command")
.argument("<files...>", "files or wildcard patterns")
.option("-n, --number-all", "number all lines")
.option("-b, --number-nonempty", "number non-empty lines")
.action((patterns, options) => {
let allFiles = [];
patterns.forEach((p) => {
allFiles = allFiles.concat(expandWildcard(p));
});
allFiles.forEach((file) => printFile(file, options));
});
program.parse();