File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
implement-shell-tools/cat Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ import { readFile , stat } from 'node:fs/promises' ;
2+ import { program } from 'commander' ;
3+
4+ program
5+ . name ( 'cat' )
6+ . description ( 'Prints contents of files' )
7+ . option ( '-n, --number-all-lines' , 'Number all output lines' )
8+ . option ( '-b, --number-non-blank' , 'Number non-blank output lines' )
9+ . argument ( '<files...>' , 'Files to read' )
10+ program . parse ( ) ;
11+
12+ const { numberAllLines, numNotBlank } = program . opts ( ) ;
13+ const files = program . args ;
14+
15+ let lineNumber = 1 ;
16+
17+ for ( const file of files ) {
18+ try {
19+ const fileStat = await stat ( file ) ;
20+ if ( fileStat . isDirectory ( ) ) {
21+ console . error ( `cat: ${ file } : Is a directory` ) ;
22+ continue ;
23+ }
24+ const content = await readFile ( file , 'utf-8' ) ;
25+ const lines = content . split ( '\n' ) ;
26+
27+ for ( const line of lines ) {
28+ const shouldNumber = ( numberAllLines && ! numNotBlank ) || ( numNotBlank && line . trim ( ) !== '' ) ;
29+
30+ if ( shouldNumber ) {
31+ console . log ( `${ lineNumber . toString ( ) . padStart ( 6 ) } ${ line } ` ) ;
32+ lineNumber ++ ;
33+ } else {
34+ console . log ( line ) ;
35+ }
36+ }
37+ } catch ( err ) {
38+ console . error ( `cat: ${ file } : ${ err . message } ` ) ;
39+ }
40+ }
You can’t perform that action at this time.
0 commit comments