Skip to content

Commit f8562b3

Browse files
committed
ls bugs were fixec
1 parent a6701f1 commit f8562b3

1 file changed

Lines changed: 37 additions & 25 deletions

File tree

  • implement-shell-tools/ls

implement-shell-tools/ls/ls.js

Lines changed: 37 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ const args = process.argv.slice(2);
44

55
let onePerLine = false;
66
let showHidden = false;
7-
let path = "."; // Current directory by default
7+
let paths = [];
88

99
// Check for flags
1010
for (let i = 0; i < args.length; i++) {
@@ -13,37 +13,49 @@ for (let i = 0; i < args.length; i++) {
1313
} else if (args[i] === "-a") {
1414
showHidden = true;
1515
} else {
16-
path = args[i];
16+
paths.push(args[i]);
1717
}
1818
}
1919

20-
try {
21-
// Check if the path is a file
22-
if (fs.statSync(path).isFile()) {
23-
console.log(path);
24-
} else {
25-
let files = fs.readdirSync(path);
26-
27-
// Print each file
28-
for (let i = 0; i < files.length; i++) {
29-
let file = files[i];
20+
// Use current directory if no path is given
21+
if (paths.length === 0) {
22+
paths.push(".");
23+
}
3024

31-
// Skip hidden files unless -a is used
32-
if (!showHidden && file.startsWith(".")) {
33-
continue;
25+
for (let i = 0; i < paths.length; i++) {
26+
let path = paths[i];
27+
28+
try {
29+
// Check if the path is a file
30+
if (fs.statSync(path).isFile()) {
31+
console.log(path);
32+
} else {
33+
let files = fs.readdirSync(path);
34+
35+
// Sort files like ls command
36+
files.sort();
37+
38+
// Print each file
39+
for (let j = 0; j < files.length; j++) {
40+
let file = files[j];
41+
42+
// Skip hidden files unless -a is used
43+
if (!showHidden && file.startsWith(".")) {
44+
continue;
45+
}
46+
47+
if (onePerLine) {
48+
console.log(file);
49+
} else {
50+
process.stdout.write(file + " ");
51+
}
3452
}
3553

36-
if (onePerLine) {
37-
console.log(file);
38-
} else {
39-
process.stdout.write(file + " ");
54+
if (!onePerLine) {
55+
console.log();
4056
}
4157
}
42-
43-
if (!onePerLine) {
44-
console.log();
45-
}
58+
} catch (error) {
59+
console.log("Cannot access: " + path);
4660
}
47-
} catch (error) {
48-
console.log("Cannot access: " + path);
4961
}

0 commit comments

Comments
 (0)