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