Skip to content

Commit b5dedf5

Browse files
committed
cat command
1 parent 4350f48 commit b5dedf5

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

implement-shell-tools/cat/cat.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import process from "node:process";
2+
import { promises as fs } from "node:fs";
3+
4+
const argv = process.argv.slice(2, process.argv.length);
5+
const flags = [];
6+
const paths = [];
7+
for (let i = 0; i < argv.length; i++) {
8+
if (argv[i][0] == "-") {
9+
flags.push(argv[i]);
10+
} else {
11+
paths.push(argv[i]);
12+
}
13+
}
14+
15+
displayFiles(paths, flags);
16+
17+
async function displayFiles(paths, flags) {
18+
let content = '';
19+
for (let i = 0; i < paths.length; i++) {
20+
content += await fs.readFile(paths[i], "utf-8");
21+
}
22+
23+
const lines = content.split("\n");
24+
if (lines[lines.length - 1] == '') {
25+
lines.pop();
26+
}
27+
let lineNumber = 1;
28+
for (let i = 0; i < lines.length; i++) {
29+
let output = lines[i];
30+
if (
31+
(flags.includes("-n") && !flags.includes("-b")) ||
32+
(flags.includes("-b") && lines[i] != "")
33+
) {
34+
output = " " + (lineNumber).toString() + " " + lines[i];
35+
lineNumber++;
36+
}
37+
console.log(output);
38+
}
39+
}
40+

implement-shell-tools/package.json

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{
2+
"name": "implement-shell-tools",
3+
"version": "1.0.0",
4+
"type": "module",
5+
"description": "Your task is to re-implement shell tools you have used.",
6+
"main": "index.js",
7+
"scripts": {
8+
"test": "echo \"Error: no test specified\" && exit 1"
9+
},
10+
"keywords": [],
11+
"author": "",
12+
"license": "ISC"
13+
}

0 commit comments

Comments
 (0)