-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathls.js
More file actions
66 lines (58 loc) · 1.65 KB
/
ls.js
File metadata and controls
66 lines (58 loc) · 1.65 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
import process from "node:process";
import { promises as fs } from "node:fs";
import { program } from "commander";
program
.option("-1, --one-per-line", "list one file per line")
.option("-a, --all", "do not ignore entries starting with .")
.parse();
const cliOptions = program.opts();
const cliArguments = program.args;
async function runLsCommand() {
try {
// determine directory path (use current directory when none provided)
let directoryPath;
if (cliArguments.length === 0) {
directoryPath = ".";
} else {
directoryPath = cliArguments[0];
}
// read directory entries
const directoryEntries = await fs.readdir(directoryPath);
// filter out dotfiles unless --all was provided
const visibleEntries = [];
if (cliOptions.all) {
for (const name of directoryEntries) {
visibleEntries.push(name);
}
} else {
for (const name of directoryEntries) {
if (!name.startsWith(".")) {
visibleEntries.push(name);
}
}
}
// build output
let outputString = "";
if (cliOptions.onePerLine) {
for (const name of visibleEntries) {
outputString += name + "\n";
}
// if there are no entries, outputString stays empty
} else {
for (let i = 0; i < visibleEntries.length; i++) {
if (i > 0) {
outputString += " ";
}
outputString += visibleEntries[i];
}
if (outputString !== "") {
outputString += "\n";
}
}
process.stdout.write(outputString);
} catch (err) {
console.error("Error reading directory:", err);
process.exitCode = 1;
}
}
runLsCommand();