Skip to content

Commit 5684c37

Browse files
committed
Implement ls command to list files in directory with -1 flag and -a flag
1 parent 6dd0b3a commit 5684c37

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

  • implement-shell-tools/ls

implement-shell-tools/ls/ls.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { program } from "commander";
2+
import { promises as fs } from "node:fs";
3+
4+
program
5+
.name("list-files-in-directory")
6+
.description("Implement ls command to list files in directory")
7+
.option("-1, --one-per-line", "list files one per line")
8+
.option("-a, --allFiles", "list all files including hidden ones")
9+
.argument("[paths...]", "File paths to process");
10+
11+
program.parse(process.argv);
12+
13+
// options and path from commander.
14+
const opts = program.opts();
15+
16+
let paths = program.args; // array of paths user typed
17+
if (paths.length === 0) {
18+
paths = ["."];
19+
}
20+
21+
for (const directoryPath of paths) {
22+
let entries;
23+
try {
24+
entries = await fs.readdir(directoryPath);
25+
} catch (err) {
26+
console.error(`ls: cannot access '${directoryPath}': ${err.message}`);
27+
continue; // move to next path if this one fails
28+
}
29+
30+
if (!opts.allFiles) {
31+
entries = entries.filter((name) => !name.startsWith("."));
32+
}
33+
34+
if (opts.onePerLine) {
35+
entries.forEach((name) => {
36+
console.log(name);
37+
});
38+
} else {
39+
//print files in one line if -1 is not used
40+
console.log(entries.join(" "));
41+
}
42+
}

0 commit comments

Comments
 (0)