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 process from "node:process " ;
1+ import { program } from "commander " ;
22import { promises as fs } from "node:fs" ;
33
4- const args = process . argv . slice ( 2 ) ;
4+ program
5+ . name ( "ls" )
6+ . description ( "List directory contents" )
7+ . option ( "-a, --all" , "show hidden files" )
8+ . option ( "-1, --one-per-line" , "display one file per line" )
9+ . argument ( "[path]" , "directory to list" , "." ) ;
510
6- let showAll = false ;
7- let path = "." ;
8-
9-
10- for ( const arg of args ) {
11- if ( arg === "-a" ) {
12- showAll = true ;
13- } else if ( arg === "-1" ) {
14- // do nothing: already printing one file per line
15- path = arg ;
16- }
17- }
11+ program . parse ( ) ;
1812
13+ const options = program . opts ( ) ;
14+ const path = program . args [ 0 ] || "." ;
1915
2016const files = await fs . readdir ( path ) ;
2117
22- for ( const file of files ) {
18+ const filteredFiles = files . filter ( ( file ) => {
19+ return options . all || ! file . startsWith ( "." ) ;
20+ } ) ;
2321
24- if ( ! showAll && file . startsWith ( "." ) ) {
25- continue ;
22+ if ( options . onePerLine ) {
23+ for ( const file of filteredFiles ) {
24+ console . log ( file ) ;
2625 }
27-
28- console . log ( file ) ;
29- }
30-
31- // We already print one file per line because
32- // console.log(file) automatically puts each file on its own line.
26+ } else {
27+ console . log ( filteredFiles . join ( " " ) ) ;
28+ }
You can’t perform that action at this time.
0 commit comments