1+
2+ import { program } from "commander" ;
3+ import { promises as fs } from "node:fs" ;
4+ import process from "node:process" ;
5+
6+ program
7+ . name ( "read-files-content" )
8+ . description ( "Read the content of a file (simulating cat command)" )
9+ . option ( "-n, --number" , "Number of lines" )
10+ . option ( "-b" , "Number of no-blanks lines" )
11+ . argument ( '[paths...]' , "sample-files/1.txt" ) ;
12+
13+
14+ program . parse ( ) ;
15+
16+ const argv = program . args ;
17+ console . log ( argv ) ;
18+
19+ if ( argv . length === 0 ) {
20+ console . error ( `Expected file path(s),passed but got ${ argv . length } .` ) ;
21+ process . exit ( 1 ) ;
22+ }
23+
24+
25+ for ( const path of argv ) {
26+ const option = program . opts ( ) ;
27+ const content = await fs . readFile ( path , "utf-8" ) ;
28+ if ( option . number ) {
29+ // split content
30+ let lines = content . split ( / \n / ) ;
31+ // removes last line
32+ if ( lines [ lines . length - 1 ] === "" ) {
33+ lines = lines . slice ( 0 , - 1 ) ;
34+ }
35+ lines
36+ . map ( ( line , index ) => `${ ( index + 1 ) . toString ( ) . padStart ( 6 ) } \t${ line } ` )
37+ . forEach ( line => console . log ( line ) )
38+ } else if ( option . b ) {
39+ let lines = content . split ( "\n" ) ;
40+ let linesCounter = 0 ;
41+ if ( lines [ lines . length - 1 ] === "" ) {
42+ lines = lines . slice ( 0 , - 1 ) ;
43+ }
44+ lines
45+ . map ( ( line ) => {
46+ if ( line . trim ( ) . length > 0 ) {
47+ linesCounter ++ ;
48+ return `${ linesCounter . toString ( ) . padStart ( 6 ) } \t${ line } `
49+ } else {
50+ return `${ line } `
51+ } }
52+ )
53+ . forEach ( line => console . log ( line ) )
54+ } else {
55+ const output = content . endsWith ( "\n" ) ? content . slice ( 0 , - 1 ) : content ;
56+ console . log ( output ) ;
57+ }
58+ }
0 commit comments