Skip to content

Commit b945902

Browse files
added code for the cat file exercises
1 parent 57a3c2a commit b945902

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

implement-shell-tools/cat/cat.mjs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { readFile, stat } from 'node:fs/promises';
2+
import { program } from 'commander';
3+
4+
program
5+
.name('cat')
6+
.description('Prints contents of files')
7+
.option('-n, --number-all-lines', 'Number all output lines')
8+
.option('-b, --number-non-blank', 'Number non-blank output lines')
9+
.argument('<files...>', 'Files to read')
10+
program.parse();
11+
12+
const { numberAllLines, numNotBlank } = program.opts();
13+
const files = program.args;
14+
15+
let lineNumber = 1;
16+
17+
for (const file of files) {
18+
try {
19+
const fileStat = await stat(file);
20+
if (fileStat.isDirectory()) {
21+
console.error(`cat: ${file}: Is a directory`);
22+
continue;
23+
}
24+
const content = await readFile(file, 'utf-8');
25+
const lines = content.split('\n');
26+
27+
for (const line of lines) {
28+
const shouldNumber = (numberAllLines && !numNotBlank) || (numNotBlank && line.trim() !== '');
29+
30+
if (shouldNumber) {
31+
console.log(`${lineNumber.toString().padStart(6)} ${line}`);
32+
lineNumber++;
33+
} else {
34+
console.log(line);
35+
}
36+
}
37+
} catch (err) {
38+
console.error(`cat: ${file}: ${err.message}`);
39+
}
40+
}

0 commit comments

Comments
 (0)