Skip to content

Commit cf41592

Browse files
authored
Implement ls command to list directory contents
1 parent 8cd986e commit cf41592

File tree

1 file changed

+86
-0
lines changed
  • implement-shell-tools/ls

1 file changed

+86
-0
lines changed

implement-shell-tools/ls/ls.js

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import { promises as fs } from "node:fs";
2+
import process from "node:process";
3+
import path from "node:path";
4+
import { program } from "commander";
5+
6+
program
7+
.name("ls")
8+
.description("Shows files in directory")
9+
.option("-1", "list one file per line")
10+
.option(
11+
"-a",
12+
"Used to list all files, including hidden files, in the current directory"
13+
)
14+
.argument("[sample-files]", "The file path to process");
15+
16+
program.parse();
17+
18+
let pathToFile = "";
19+
20+
const programArgv = program.args;
21+
22+
(async () => {
23+
if (programArgv.length === 1) {
24+
pathToFile = programArgv[0];
25+
try {
26+
const stats = await fs.stat(pathToFile);
27+
if (stats.isFile()) {
28+
await listFiles("file");
29+
} else if (stats.isDirectory()) {
30+
listFiles("directory");
31+
} else {
32+
console.error("Not a file or directory.");
33+
}
34+
} catch (err) {
35+
console.error("Invalid path:", err.message);
36+
}
37+
} else if (programArgv.length === 0) {
38+
pathToFile = process.cwd();
39+
await listFiles("directory");
40+
} else {
41+
console.error(
42+
`Expected no more than 1 argument (sample-files) but got ${programArgv.length}.`
43+
);
44+
}
45+
})();
46+
47+
const flag_1 = (files) => {
48+
files.forEach(function (file) {
49+
console.log(file);
50+
});
51+
};
52+
53+
const flag_a = (files) => {
54+
files.unshift("..");
55+
files.unshift(".");
56+
return files;
57+
};
58+
59+
async function listFiles(type) {
60+
let output = [];
61+
let formattedPath = "";
62+
if (type == "directory") {
63+
formattedPath = pathToFile;
64+
} else if (type == "file") {
65+
formattedPath = path.dirname(pathToFile);
66+
}
67+
const char = program.opts();
68+
const files = await fs.readdir(formattedPath);
69+
const sortedOutput = files.sort((a, b) => a.localeCompare(b));
70+
71+
if (char["a"]) {
72+
output = flag_a(sortedOutput);
73+
} else {
74+
sortedOutput.forEach(function (file) {
75+
if (file[0] != ".") {
76+
output.push(file);
77+
}
78+
});
79+
}
80+
81+
if (char["1"]) {
82+
flag_1(output);
83+
} else {
84+
console.log(output.join(" "));
85+
}
86+
}

0 commit comments

Comments
 (0)