1- import process from "node:process"
1+ import { program } from "commander" ;
22import { promises as fs } from "node:fs"
33
4- const argv = process . argv . slice ( 2 )
54
6- if ( argv . length != 1 ) {
7- console . error (
8- `Expected exactly 1 argument (a path) to be passed but got ${ argv . length } .`
9- ) ;
10- process . exit ( 1 ) ;
11- }
5+ //here we Configure the program: what flags and arguments it accepts
6+ // .option("short, long", "description")
7+ //The < > brackets mean "required"
8+
9+ program
10+ . name ( "cat" )
11+ . description ( "concatenate and print files" )
12+ . option ( "-n, --number" , "Number all output lines" )
13+ . argument ( "<path>" , "The file path to process" ) ;
14+
15+ // here Parse command line arguments (reads process.argv and interprets it)
16+ program . parse ( ) ;
1217
13- const path = argv [ 0 ]
1418
19+ // Get the parsed values
20+ const path = program . args [ 0 ] ; // The filename user provided
21+ const hasNumberFlag = program . opts ( ) . number ; // True if user used -n flag
1522
23+ //read the file
1624const content = await fs . readFile ( path , "utf-8" )
17- console . log ( content )
25+
26+ // Output with or without line numbers
27+ if ( hasNumberFlag ) {
28+ // Add line numbers to each line
29+ const lines = content . split ( "\n" ) ; // Split into array of lines
30+ 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"
33+ } ) ;
34+ console . log ( numberedLines . join ( "\n" ) ) ; // Join back with newlines
35+ } else {
36+ // Just print the file as-is
37+ console . log ( content ) ;
38+ }
39+
40+
41+
42+
43+
44+
0 commit comments