1+ //On macOS (BSD cat), the -n option resets numbering for each file, so multiple files start again at 1,
2+ //when you run cat -n sample-files/*.txt
3+ //This Node.js script mimics GNU cat, where -n continues numbering across all files instead of restarting.
14import { program } from "commander" ;
25import { promises as fs } from "node:fs"
36
4-
5-
67 //configuring the program here to run flags.
78
89program
@@ -13,33 +14,43 @@ program
1314 . argument ( "<files...>" , "File paths to display" )
1415 . parse ( process . argv ) ; //Parse command line arguments (reads process.argv and interprets it)
1516
17+
18+ //Constants
19+ const paddingWidth = 6 ; // width for line number padding
20+
21+ // Helper function to format a line with numbering
22+ function formatLine ( line , lineNumber , numberAll , numberNonBlank ) {
23+ if ( numberAll ) {
24+ return `${ lineNumber . toString ( ) . padStart ( paddingWidth ) } ${ line } ` ;
25+ }
26+ if ( numberNonBlank ) {
27+ if ( line . trim ( ) === "" ) {
28+ return line ; // blank line, no number
29+ }
30+ return `${ lineNumber . toString ( ) . padStart ( paddingWidth ) } ${ line } ` ;
31+ }
32+ return line ; // no numbering
33+ }
1634const options = program . opts ( ) ;
1735const files = program . args ; // Array of file paths passed as arguments
1836
19- let lineNumber = 1 ; // shared across all files, like GNU cat -n)
37+ let lineNumber = 1 ; // shared across all files
2038
2139for ( const file of files ) {
2240 const content = await fs . readFile ( file , "utf-8" ) ;
23- const lines = content . split ( "\n" ) ;
41+ let lines = content . split ( "\n" ) ;
42+ // Remove trailing empty line if file ends with newline
43+ if ( lines . length > 0 && lines [ lines . length - 1 ] === "" ) {
44+ lines . pop ( ) ;
45+ }
2446
2547 for ( const line of lines ) {
26-
27- if ( options . number ) {
28- console . log ( `${ lineNumber . toString ( ) . padStart ( 6 ) } ${ line } ` ) ; // adding padding for formatting
48+ const formatted = formatLine ( line , lineNumber , options . number , options . numberNonblank ) ;
49+ console . log ( formatted ) ;
50+
51+ // Increment line number if numbering applies
52+ if ( options . number || ( options . numberNonblank && line . trim ( ) !== "" ) ) {
2953 lineNumber ++ ;
30- }
31- else if ( options . numberNonblank ) { // -b
32- if ( line . trim ( ) === "" ) {
33- console . log ( line ) ;
34- } else {
35- console . log ( `${ lineNumber . toString ( ) . padStart ( 6 ) } ${ line } ` ) ;
36- lineNumber ++ ;
37- }
38- } else {
39- console . log ( line ) ;
40- }
4154 }
4255 }
43-
44-
45-
56+ }
0 commit comments