-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathls.js
More file actions
39 lines (32 loc) · 1.23 KB
/
ls.js
File metadata and controls
39 lines (32 loc) · 1.23 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
import { program } from "commander";
import { promises as fs } from "node:fs";
//configuring
program
.name("ls")
.description("list directory contents")
.option("-1, --one", "Outputs are printed one entry per line")
.option("-a, --all","Show all files including hidden files that start with a .")
.argument("[directory]", "Directory to list", "."); // "." means current directory
//interpret the program
program.parse();
const options = program.opts();
const directory = program.args[0] || "."; //get dir arg- 1st arg in program.args array || if no arg default to current dir
let files = await fs.readdir(directory); //read the dir to get array of filenames
//Handle -a (include hidden files)
// Node's fs.readdir() does not include the special directory entries "." (current dir)
// and ".." (parent dir). The real `ls -a` command shows them, so we add them manually here
// to match the behavior of `ls -a`.
if (options.all) {
files.unshift("..");
files.unshift(".");
} else {
files = files.filter(name => !name.startsWith("."));
}
if (options.one) { // Print each file on its own line
for (const file of files) {
console.log(file);
}
}
else {
console.log(files.join(" "));// Default: join with spaces (like ls without -1)
}