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 11import { program } from "commander" ;
2- import { error } from "node:console" ;
32import { promises as fs } from "node:fs" ;
43
54program
65 . name ( "cat" )
76 . description ( "cat sample-files/1.txt " )
7+ . option ( "-n" , "number all lines" )
88 . argument ( "<path>" , "The file path to process" ) ;
99program . parse ( ) ;
1010
@@ -18,7 +18,19 @@ if (argv.length != 1) {
1818const path = argv [ 0 ] ;
1919try {
2020 const content = await fs . readFile ( path , "utf-8" ) ;
21- process . stdout . write ( content ) ;
21+
22+ const addLineNumber = program . opts ( ) ;
23+ if ( addLineNumber . n ) {
24+ const lines = content . split ( "\n" ) ;
25+
26+ if ( lines [ lines . length - 1 ] === "" ) {
27+ lines . pop ( ) ;
28+ }
29+
30+ lines . forEach ( ( line , index ) => {
31+ process . stdout . write ( `${ index + 1 } ${ line } \n` ) ;
32+ } ) ;
33+ } else process . stdout . write ( content ) ;
2234} catch ( error ) {
2335 console . error ( error . message ) ;
2436 process . exit ( 1 ) ;
You can’t perform that action at this time.
0 commit comments