Skip to content

Commit e66f6f3

Browse files
committed
add ls.js file in
1 parent 2213c39 commit e66f6f3

1 file changed

Lines changed: 57 additions & 0 deletions

File tree

  • implement-shell-tools/ls

implement-shell-tools/ls/ls.js

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
const fs = require("fs");
2+
const path = require("path");
3+
4+
const args = process.argv.slice(2);
5+
6+
let oneLine = false;
7+
let showHidden = false;
8+
let targets = [];
9+
10+
for (const arg of args) {
11+
if (arg === "-1") {
12+
oneLine = true;
13+
} else if (arg === "-a") {
14+
showHidden = true;
15+
} else {
16+
targets.push(arg);
17+
}
18+
}
19+
20+
if (targets.length === 0) {
21+
targets.push(".");
22+
}
23+
24+
function listDirectory(directory) {
25+
let files = fs.readdirSync(directory);
26+
27+
if (!showHidden) {
28+
files = files.filter(file => !file.startsWith("."));
29+
}
30+
31+
files.sort();
32+
33+
if (oneLine) {
34+
console.log(files.join("\n"));
35+
} else {
36+
console.log(files.join(" "));
37+
}
38+
}
39+
40+
function listTarget(target) {
41+
try {
42+
const stats = fs.statSync(target);
43+
44+
if (stats.isDirectory()) {
45+
listDirectory(target);
46+
} else {
47+
console.log(target);
48+
}
49+
50+
} catch (error) {
51+
console.error(`ls: cannot access '${target}': No such file or directory`);
52+
}
53+
}
54+
55+
for (const target of targets) {
56+
listTarget(target);
57+
}

0 commit comments

Comments
 (0)