1- import { program } from "commander" ;
2- import { promises as fs } from "node:fs"
3-
1+ import { program } from "commander" ;
2+ import { promises as fs } from "node:fs" ;
43
54//here we Configure the program: what flags and arguments it accepts
65// .option("short, long", "description")
@@ -10,35 +9,46 @@ program
109 . name ( "cat" )
1110 . description ( "concatenate and print files" )
1211 . option ( "-n, --number" , "Number all output lines" )
12+ . option ( "-b, --numberNonBlank" , "Number non-blank output lines" )
1313 . argument ( "<path>" , "The file path to process" ) ;
1414
1515// here Parse command line arguments (reads process.argv and interprets it)
1616program . parse ( ) ;
1717
18-
1918// Get the parsed values
2019const path = program . args [ 0 ] ; // The filename user provided
21- const hasNumberFlag = program . opts ( ) . number ; // True if user used -n flag
20+ const hasNumberFlag = program . opts ( ) . number ; // True if user used -n flag
21+ const hasBFlag = program . opts ( ) . numberNonBlank ;
2222
2323//read the file
24- const content = await fs . readFile ( path , "utf-8" )
24+ const content = await fs . readFile ( path , "utf-8" ) ;
2525
2626// Output with or without line numbers
2727if ( hasNumberFlag ) {
28+
2829 // Add line numbers to each line
2930 const lines = content . split ( "\n" ) ; // Split into array of lines
3031 const numberedLines = lines . map ( ( line , index ) => {
31- const numberOfLine = index + 1 ; // Convert 0-based index to 1-based line number
32- return `${ numberOfLine } ${ line } ` ; // Format: " 1 Hello"
32+ const lineNumber = index + 1 ; // Convert 0-based index to 1-based line number
33+ return `${ lineNumber } ${ line } ` ; // Format: " 1 Hello"
3334 } ) ;
3435 console . log ( numberedLines . join ( "\n" ) ) ; // Join back with newlines
36+ } else if ( hasBFlag ) {
37+ console . log ( "Using -b flag!" ) ;
38+ let lineNumber = 0 ;
39+ const lines = content . split ( "\n" ) ;
40+ console . log ( "Total lines:" , lines . length ) ;
41+ const numberedLines = lines . map ( ( line ) => {
42+ console . log ( `Line: "${ line } ", isEmpty: ${ line . trim ( ) === "" } ` ) ;
43+ if ( line . trim ( ) === "" ) {
44+ return line ;
45+ } else {
46+ lineNumber = lineNumber + 1 ;
47+ return ` ${ lineNumber } ${ line } `
48+ }
49+ } ) ;
50+ console . log ( numberedLines . join ( "\n" ) ) ;
3551} else {
3652 // Just print the file as-is
3753 console . log ( content ) ;
3854}
39-
40-
41-
42-
43-
44-
0 commit comments