Skip to content

Commit 287fd3a

Browse files
committed
add try/catch for ls
1 parent 9139868 commit 287fd3a

1 file changed

Lines changed: 14 additions & 5 deletions

File tree

  • implement-shell-tools/ls

implement-shell-tools/ls/ls.mjs

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,21 @@ program
55
.name("ls")
66
.description("List all the files in a directory")
77
.option("-a, --all", "Include hidden files")
8-
.option("-1", "One entry per line")
9-
.argument("[dir]", "directory to list", ".");
8+
.option("-1, --one", "One entry per line")
9+
.argument("[dir]", "directory to list");
1010

1111
program.parse();
1212

1313
const options = program.opts();
1414
const dir = program.args[0] || ".";
1515

16-
const entries = await fs.readdir(dir, { withFileTypes: true });
16+
let entries;
17+
try {
18+
entries = await fs.readdir(dir, { withFileTypes: true });
19+
} catch (err) {
20+
console.error(`Error accessing ${dir}: ${err.message}`);
21+
process.exit(1);
22+
}
1723

1824
const visibleNames = [];
1925

@@ -22,8 +28,11 @@ for(const entry of entries){
2228
visibleNames.push(entry.name);
2329
}
2430

25-
if(options["1"]){
31+
if (options.all) {
32+
visibleNames.unshift(".", "..");
33+
}
34+
if(options.one){
2635
console.log(visibleNames.join("\n"));
2736
} else{
2837
console.log(visibleNames.join(" "));
29-
}
38+
}

0 commit comments

Comments
 (0)