-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathcat.mjs
More file actions
49 lines (41 loc) · 1.4 KB
/
cat.mjs
File metadata and controls
49 lines (41 loc) · 1.4 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
import {program} from 'commander';
import {promises as fs} from 'node:fs';
import process from 'node:process';
program
.name('cat')
.description('Concatenates and prints the contents of files.')
.argument('<paths...>', 'The paths to the files to concatenate')
.option('-n, --number', 'Number all output lines')
.option('-b, --number-nonblank', 'Number nonempty output lines');
program.parse();
const argv = program.args;
const options = program.opts();
if (argv.length < 1) {
console.error(
`Expected at least 1 argument (a path) to be passed but got ${argv.length}.`,
);
process.exit(1);
}
let showLineNumbers = options.number || false;
let showNonEmptyLineNumbers = options.numberNonblank || false;
if (showLineNumbers && showNonEmptyLineNumbers) {
showLineNumbers = false;
}
let lineNumber = 1;
const spacer = ' ';
for (const path of argv) {
const content = await fs.readFile(path, 'utf-8');
const lines = content.split('\n');
while (lines.length > 0 && lines[lines.length - 1] === '') {
lines.pop();
}
for (const line of lines) {
if (showLineNumbers) {
process.stdout.write(`${spacer} ${lineNumber++} ${line}\n`);
} else if (showNonEmptyLineNumbers && line.trim() !== '') {
process.stdout.write(`${spacer} ${lineNumber++} ${line}\n`);
} else {
process.stdout.write(`${line}\n`);
}
}
}