File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import { program } from "commander" ;
2+ import { promises as fs } from "node:fs" ;
3+
4+ program
5+ . name ( "ls" )
6+ . description ( "List the file directory" )
7+ . option ( "-1" , "List one file per line" )
8+ . option ( "-a" , "Include hidden file" )
9+ . argument ( "[dir]" , "Directory to list" , "." )
10+ . parse ( ) ;
11+
12+ const options = program . opts ( ) ;
13+ const dir = program . args [ 0 ] || "." ;
14+
15+ try {
16+ const items = await fs . readdir ( dir , { withFileTypes : true } ) ;
17+
18+ let fileNames = items . map ( item => item . name ) ;
19+
20+ // Filter out hidden files unless -a
21+ if ( ! options . a ) {
22+ fileNames = fileNames . filter ( name => ! name . startsWith ( "." ) ) ;
23+ }
24+
25+ // Print output
26+ if ( options [ "1" ] ) {
27+ // One file per line
28+ fileNames . forEach ( name => console . log ( name ) ) ;
29+ } else {
30+ // Default: space-separated (like regular `ls`)
31+ console . log ( fileNames . join ( " " ) ) ;
32+ }
33+ } catch ( err ) {
34+ console . error ( `Error reading directory "${ dir } ":` , err . message ) ;
35+ process . exit ( 1 ) ;
36+ }
37+
You can’t perform that action at this time.
0 commit comments