@@ -5,18 +5,44 @@ import process from "node:process";
55program
66 . name ( "mycat" )
77 . description ( "Outputs the content of the given file(s), like the cat command" )
8- . argument ( "<path>" , "The file path to read" ) ;
8+ . option ( "-n" , "Number all lines" )
9+ . option ( "-b" , "Number non-blank lines only" )
10+ . argument ( "<files...>" , "File paths to display" ) ;
911
1012program . parse ( ) ;
1113
12- const argv = program . args ;
13- if ( argv . length !== 1 ) {
14- console . error (
15- `Expected exactly 1 argument (a path) to be passed but got ${ argv . length } .`
16- ) ;
17- process . exit ( 1 ) ;
18- }
14+ const options = program . opts ( ) ;
15+ const filePaths = program . args ;
16+
17+ let lineNumber = 1 ;
18+
19+ for ( const path of filePaths ) {
20+ try {
21+ const content = await fs . readFile ( path , "utf-8" ) ;
22+ const lines = content . trimEnd ( ) . split ( "\n" ) ;
1923
20- const path = argv [ 0 ] ;
21- const content = await fs . readFile ( path , "utf-8" ) ;
22- process . stdout . write ( content ) ;
24+ for ( const line of lines ) {
25+ const isBlank = line . trim ( ) === "" ;
26+
27+ if ( options . b ) {
28+ // -b: number only non-blank lines
29+ if ( ! isBlank ) {
30+ process . stdout . write ( `${ String ( lineNumber ) . padStart ( 6 ) } ${ line } \n` ) ;
31+ lineNumber ++ ;
32+ } else {
33+ process . stdout . write ( "\n" ) ;
34+ }
35+ } else if ( options . n ) {
36+ // -n: number all lines
37+ process . stdout . write ( `${ String ( lineNumber ) . padStart ( 6 ) } ${ line } \n` ) ;
38+ lineNumber ++ ;
39+ } else {
40+ // no flags
41+ process . stdout . write ( line + "\n" ) ;
42+ }
43+ }
44+ } catch ( error ) {
45+ process . stderr . write ( `Error reading file ${ path } : ${ error . message } \n` ) ;
46+ process . exit ( 1 ) ;
47+ }
48+ }
0 commit comments