Skip to content

Commit 72159a9

Browse files
committed
ls - implement-shell-tools
1 parent 35a7ae4 commit 72159a9

3 files changed

Lines changed: 87 additions & 0 deletions

File tree

implement-shell-tools/ls/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: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"name": "ls",
3+
"version": "1.0.0",
4+
"description": "You should already be familiar with the `ls` command line tool.",
5+
"main": "script-01.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1"
8+
},
9+
"keywords": [],
10+
"author": "",
11+
"license": "ISC",
12+
"dependencies": {
13+
"comander": "^0.0.1-security",
14+
"commander": "^14.0.2"
15+
}
16+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#!/usr/bin/env node
2+
import { program } from "commander";
3+
import fs from "fs";
4+
import path from "path";
5+
6+
// Define CLI
7+
program
8+
.name("ls-clone")
9+
.description("A simple implementation of ls")
10+
.option("-1", "list one file per line")
11+
.option("-a", "include hidden files")
12+
.argument("[dirs...]", "directories to list", "."); // default is current dir
13+
14+
program.parse();
15+
16+
const options = program.opts();
17+
const dirs = program.args.length ? program.args : ["."];
18+
const onePerLine = options["1"];
19+
const showAll = options.a;
20+
21+
for (const dir of dirs) {
22+
let files;
23+
try {
24+
files = fs.readdirSync(dir);
25+
} catch (err) {
26+
console.error(`ls-clone: cannot access '${dir}': No such file or directory`);
27+
continue;
28+
}
29+
30+
if (!showAll) {
31+
files = files.filter(name => !name.startsWith("."));
32+
}
33+
34+
// Output
35+
if (onePerLine) {
36+
files.forEach(f => console.log(f));
37+
} else {
38+
console.log(files.join(" "));
39+
}
40+
}

0 commit comments

Comments
 (0)