-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcat.js
More file actions
76 lines (66 loc) · 2.04 KB
/
cat.js
File metadata and controls
76 lines (66 loc) · 2.04 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 fs = require('fs');
const path = require('path');
//shared line counter across all files(matches cat -n)
let globalLineCounter = 1;
function printFile(filePath, options) {
try {
const content = fs.readFileSync(filePath, 'utf-8');
const lines = content.split('\n');
lines.forEach((line) => {
if(options.numberNonEmpty) {
//-b option: number non-empty lines
if(line.trim()) {
process.stdout.write(
`${String(globalLineCounter).padStart(6)}\t${line}\n`
);
globalLineCounter++;
} else {
process.stdout.write('\n');
}
} else if(options.numberAll) {
//-n option: number all lines
process.stdout.write(
`${String(globalLineCounter).padStart(6)}\t${line}\n`
);
globalLineCounter++;
} else {
//default: just print the line
process.stdout.write(line + '\n');
}
});
} catch (error) {
console.error(`Error reading file ${filePath}: ${error.message}`);
}
}
function main() {
const args = process.argv.slice(2);
const options = {
numberNonEmpty: false,
numberAll: false,
};
const filePatterns = [];
args.forEach((arg) => {
if(arg === '-n') {
options.numberAll = true;
} else if(arg === '-b') {
options.numberNonEmpty = true;
} else {
filePatterns.push(arg);
}
});
// -b takes precedence over -n
if(options.numberNonEmpty) {
options.numberAll = false;
}
if(filePatterns.length === 0) {
console.log("cat: missing file operand");
process.exit(1);
}
const files = filePatterns;
files.forEach((file) => {
const resolvedPath = path.resolve(process.cwd(), file);
printFile(resolvedPath, options);
});
}
main();