Skip to content

Commit 7e7ebfd

Browse files
committed
cat done
1 parent 4350f48 commit 7e7ebfd

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

implement-shell-tools/.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
node_modules/
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#!/usr/bin/env node
2+
import { program } from "commander";
3+
import { promises as fs } from "node:fs";
4+
import process from "node:process";
5+
6+
program
7+
.name("customCat")
8+
.description("CLI command to concatenate and print files")
9+
.option("-n, --number", "Number all output lines starting, at 1")
10+
.option("-b, --nonBlank", "Number only non-blank lines, starting at 1")
11+
.argument("<files...>", "Files to read");
12+
13+
program.parse();
14+
15+
const argv = program.args;
16+
const options = program.opts();
17+
18+
let lineNumber = 1;
19+
20+
for (const filePath of argv) {
21+
try {
22+
const content = await fs.readFile(filePath, "utf-8");
23+
const lines = content.split("\n");
24+
25+
if (lines[lines.length - 1] === "") lines.pop();
26+
27+
lines.forEach((line, index) => {
28+
if (options.nonBlank) {
29+
if (line.trim() !== "") {
30+
process.stdout.write(`${(index + 1).toString().padStart(6)} ${line}\n`);
31+
lineNumber++;
32+
} else process.stdout.write(`${line}\n`);
33+
} else if (options.number) {
34+
process.stdout.write(`${(index + 1).toString().padStart(6)} ${line}\n`);
35+
} else {
36+
process.stdout.write(`${line}\n`);
37+
}
38+
});
39+
} catch (error) {
40+
console.error(`customCat: ${filePath}: No such file or directory.`);
41+
}
42+
}

implement-shell-tools/package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"type": "module"
3+
}

0 commit comments

Comments
 (0)