Skip to content

Commit 4e4cf73

Browse files
committed
Refactor ls to use commander
1 parent dc403fc commit 4e4cf73

1 file changed

Lines changed: 19 additions & 23 deletions

File tree

  • implement-shell-tools/ls

implement-shell-tools/ls/ls.js

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,28 @@
1-
import process from "node:process";
1+
import { program } from "commander";
22
import { promises as fs } from "node:fs";
33

4-
const args = process.argv.slice(2);
4+
program
5+
.name("ls")
6+
.description("List directory contents")
7+
.option("-a, --all", "show hidden files")
8+
.option("-1, --one-per-line", "display one file per line")
9+
.argument("[path]", "directory to list", ".");
510

6-
let showAll = false;
7-
let path = ".";
8-
9-
10-
for (const arg of args) {
11-
if (arg === "-a") {
12-
showAll = true;
13-
} else if (arg === "-1") {
14-
// do nothing: already printing one file per line
15-
path = arg;
16-
}
17-
}
11+
program.parse();
1812

13+
const options = program.opts();
14+
const path = program.args[0] || ".";
1915

2016
const files = await fs.readdir(path);
2117

22-
for (const file of files) {
18+
const filteredFiles = files.filter((file) => {
19+
return options.all || !file.startsWith(".");
20+
});
2321

24-
if (!showAll && file.startsWith(".")) {
25-
continue;
22+
if (options.onePerLine) {
23+
for (const file of filteredFiles) {
24+
console.log(file);
2625
}
27-
28-
console.log(file);
29-
}
30-
31-
// We already print one file per line because
32-
// console.log(file) automatically puts each file on its own line.
26+
} else {
27+
console.log(filteredFiles.join(" "));
28+
}

0 commit comments

Comments
 (0)