Skip to content

Commit 996d79f

Browse files
committed
ls implementation exercise
1 parent 7395ee6 commit 996d79f

File tree

3 files changed

+76
-0
lines changed

3 files changed

+76
-0
lines changed

implement-shell-tools/ls/myls.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { program } from "commander";
2+
import { promises as fs } from "node:fs";
3+
import process from "node:process";
4+
5+
program
6+
.name("myls")
7+
.description("list file(s) in the directory, like the ls command")
8+
.option("-1", "list one file per line")
9+
.option("-a", "include hidden files")
10+
.argument("[directory]", "Directory to list", ".");
11+
12+
program.parse();
13+
14+
const options = program.opts();
15+
const directory = program.args[0] || ".";
16+
17+
try {
18+
let files = await fs.readdir(directory);
19+
20+
// if "-a" is used, include hidden files; those that start with "."
21+
if (options.a) {
22+
files = [".", "..", ...files];
23+
}
24+
25+
for (const file of files) {
26+
// if "-a" is not used, skip hidden files; those that start with "."
27+
if (!options.a && file.startsWith(".")) {
28+
continue;
29+
}
30+
31+
console.log(file); // print file name; one file per line
32+
}
33+
} catch (error) {
34+
console.error(`Error reading directory ${directory}:`, error.message);
35+
process.exit(1);
36+
}

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

Lines changed: 24 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": "index.js",
6+
"type": "module",
7+
"scripts": {
8+
"test": "echo \"Error: no test specified\" && exit 1"
9+
},
10+
"keywords": [],
11+
"author": "",
12+
"license": "ISC",
13+
"dependencies": {
14+
"commander": "^14.0.0"
15+
}
16+
}

0 commit comments

Comments
 (0)