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 ( "list-files-in-directory" )
6+ . description ( "Implement ls command to list files in directory" )
7+ . option ( "-1, --one-per-line" , "list files one per line" )
8+ . option ( "-a, --allFiles" , "list all files including hidden ones" )
9+ . argument ( "[paths...]" , "File paths to process" ) ;
10+
11+ program . parse ( process . argv ) ;
12+
13+ // options and path from commander.
14+ const opts = program . opts ( ) ;
15+
16+ let paths = program . args ; // array of paths user typed
17+ if ( paths . length === 0 ) {
18+ paths = [ "." ] ;
19+ }
20+
21+ for ( const directoryPath of paths ) {
22+ let entries ;
23+ try {
24+ entries = await fs . readdir ( directoryPath ) ;
25+ } catch ( err ) {
26+ console . error ( `ls: cannot access '${ directoryPath } ': ${ err . message } ` ) ;
27+ continue ; // move to next path if this one fails
28+ }
29+
30+ if ( ! opts . allFiles ) {
31+ entries = entries . filter ( ( name ) => ! name . startsWith ( "." ) ) ;
32+ }
33+
34+ if ( opts . onePerLine ) {
35+ entries . forEach ( ( name ) => {
36+ console . log ( name ) ;
37+ } ) ;
38+ } else {
39+ //print files in one line if -1 is not used
40+ console . log ( entries . join ( " " ) ) ;
41+ }
42+ }
You can’t perform that action at this time.
0 commit comments