Skip to content

Commit 35a7ae4

Browse files
committed
Cat - Implement-Shell-tools
1 parent 56e9757 commit 35a7ae4

3 files changed

Lines changed: 107 additions & 0 deletions

File tree

implement-shell-tools/cat/package-lock.json

Lines changed: 31 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
"type": "module",
3+
"name": "cat",
4+
"version": "1.0.0",
5+
"description": "You should already be familiar with the `cat` command line tool.",
6+
"main": "script-01.js",
7+
"scripts": {
8+
"test": "echo \"Error: no test specified\" && exit 1"
9+
10+
},
11+
"keywords": [],
12+
"author": "",
13+
"license": "ISC",
14+
"dependencies": {
15+
"comander": "^0.0.1-security",
16+
"commander": "^14.0.2"
17+
}
18+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
2+
import { program } from "commander";
3+
import { promises as fs } from "node:fs";
4+
import process from "node:process";
5+
6+
program
7+
.name("read-files-content")
8+
.description("Read the content of a file (simulating cat command)")
9+
.option("-n, --number","Number of lines")
10+
.option("-b","Number of no-blanks lines")
11+
.argument('[paths...]', "sample-files/1.txt");
12+
13+
14+
program.parse();
15+
16+
const argv = program.args;
17+
console.log(argv);
18+
19+
if (argv.length === 0) {
20+
console.error(`Expected file path(s),passed but got ${argv.length}.`);
21+
process.exit(1);
22+
}
23+
24+
25+
for (const path of argv){
26+
const option = program.opts();
27+
const content = await fs.readFile(path, "utf-8");
28+
if (option.number){
29+
// split content
30+
let lines = content.split(/\n/);
31+
// removes last line
32+
if (lines[lines.length - 1] === ""){
33+
lines = lines.slice(0,-1);
34+
}
35+
lines
36+
.map((line,index) => `${(index + 1).toString().padStart(6)}\t${line}`)
37+
.forEach(line => console.log(line))
38+
} else if (option.b){
39+
let lines = content.split("\n");
40+
let linesCounter = 0;
41+
if (lines[lines.length - 1] === ""){
42+
lines = lines.slice(0,-1);
43+
}
44+
lines
45+
.map((line) => {
46+
if (line.trim().length > 0) {
47+
linesCounter++;
48+
return `${linesCounter.toString().padStart(6)}\t${line}`
49+
}else{
50+
return `${line}`
51+
}}
52+
)
53+
.forEach(line => console.log(line))
54+
}else {
55+
const output = content.endsWith("\n") ? content.slice(0,-1) : content;
56+
console.log(output);
57+
}
58+
}

0 commit comments

Comments
 (0)