File tree Expand file tree Collapse file tree
implement-shell-tools/cat Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import { program } from "commander" ;
2+ import { promises as fs } from "node:fs" ;
3+
4+ program
5+ . name ( "cat" )
6+ . description ( "read, display, and concatenate text files." )
7+ . option ( "-n" , " Number all output lines." )
8+ . option ( "-b" , " Number non-blank output lines." )
9+ . arguments ( "<paths...>" ) ; // allow more file paths
10+
11+ program . parse ( ) ;
12+
13+ const options = program . opts ( ) ;
14+ const paths = program . args ;
15+
16+ for ( const path of paths ) {
17+ let content ;
18+ try {
19+ content = await fs . readFile ( path , "utf-8" )
20+ } catch ( err ) {
21+ console . error ( `Error reading file "${ path } ": ${ err . message } ` ) ;
22+ continue ;
23+ }
24+
25+ // split file into lines
26+ let lines = content . replace ( / \n $ / , "" ) . split ( "\n" ) ;
27+
28+ let lineNum = 1 ;
29+
30+ for ( const line of lines ) {
31+ if ( options . b ) {
32+ if ( line . trim ( ) !== "" ) {
33+ console . log ( `${ lineNum . toString ( ) . padStart ( 5 ) } ${ line } ` )
34+ lineNum ++ ;
35+ } else {
36+ console . log ( "" ) ;
37+ }
38+ } else if ( options . n ) {
39+ console . log ( `${ lineNum . toString ( ) . padStart ( 5 ) } ${ line } ` )
40+ lineNum ++ ;
41+ } else {
42+ console . log ( `${ line } ` )
43+ }
44+ }
45+ }
You can’t perform that action at this time.
0 commit comments