-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathls.js
More file actions
43 lines (33 loc) · 1.2 KB
/
ls.js
File metadata and controls
43 lines (33 loc) · 1.2 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
import { program } from "commander";
import { promises as fs } from "node:fs";
//config the program
program
.name("ls")
.description("list directory contents")
.option("-1, --one", "Force output to be one entry per line")
.option(
"-a, --all",
"shows all the files including the hidden ones which start with a dot"
)
.argument("[directory]", "Directory to list", "."); // "." means current directory
//interpret the program
program.parse();
// Get the directory argument (first argument in program.args array)
// If no argument provided, default to current directory "."
const directory = program.args[0] || ".";
//read the directory to get array of filenames
const files = await fs.readdir(directory);
//check for flags
const hasAflag = program.opts().all;
// Filter the files array BEFORE looping
// If hasAflag is true, keep all files
// If hasAflag is false, remove files that start with "."
const fileToShow = hasAflag
? files
: files.filter(file => !file.startsWith("."))
//print each file on its own line
// Note: console.log(files) would print the entire array like: ['file1', 'file2']
// Loop prints each individually on separate lines
for (const file of fileToShow) {
console.log(file)
}