File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
implement-shell-tools/ls/sample-files Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ #!/usr/bin/env node
2+ const { program } = require ( "commander" ) ;
3+ const fs = require ( "fs" ) ;
4+ const path = require ( "path" ) ;
5+
6+ function listDirectory ( dir , options ) {
7+ try {
8+ const stats = fs . statSync ( dir ) ;
9+
10+ if ( stats . isFile ( ) ) {
11+ console . log ( dir ) ;
12+ return ;
13+ }
14+ } catch ( e ) {
15+ console . error ( `ls: cannot access '${ dir } ': No such file or directory` ) ;
16+ return ;
17+ }
18+
19+ let entries ;
20+
21+ try {
22+ entries = fs . readdirSync ( dir , { withFileTypes : true } ) ;
23+ } catch ( e ) {
24+ console . error ( `ls: cannot access '${ dir } ': No such file or directory` ) ;
25+ return ;
26+ }
27+
28+ let names = entries . map ( e => e . name ) ;
29+
30+ if ( options . all ) {
31+ names . unshift ( "." , ".." ) ;
32+ } else {
33+ names = names . filter ( name => ! name . startsWith ( "." ) ) ;
34+ }
35+
36+ names . sort ( ) ;
37+ names . forEach ( name => console . log ( name ) ) ;
38+ }
39+
40+ program
41+ . name ( "myls" )
42+ . description ( "Custom implementation of ls" )
43+ . option ( "-1" , "list one file per line (default in our version)" )
44+ . option ( "-a, --all" , "include hidden files" )
45+ . argument ( "[dir]" , "directory to list" , "." )
46+ . action ( ( dir , options ) => {
47+ listDirectory ( dir , options ) ;
48+ } ) ;
49+
50+ program . parse ( ) ;
You can’t perform that action at this time.
0 commit comments