File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
Expand file tree Collapse file tree 1 file changed +38
-0
lines changed 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 ( "wc" )
6+ . description ( "Custom wc CLI - count lines, words, bytes" )
7+ . argument ( "<file>" , "File to process" )
8+ . option ( "-l" , "Print the number of lines" )
9+ . option ( "-w" , "Print the number of words" )
10+ . option ( "-c" , "Print the number of bytes" )
11+ . parse ( ) ;
12+
13+ const options = program . opts ( ) ;
14+ const filePath = program . args [ 0 ] ;
15+
16+ try {
17+ const data = await fs . readFile ( filePath , "utf-8" ) ;
18+
19+
20+
21+ const lineCount = data . split ( "\n" ) . length ;
22+ const wordCount = data . trim ( ) . split ( / \s + / ) . length ;
23+ const byteCount = data . length ;
24+
25+ const showAll = ! options . l && ! options . w && ! options . c ;
26+
27+
28+ const output = [ ] ;
29+ if ( options . l || showAll ) output . push ( lineCount . toString ( ) . padStart ( 8 ) ) ;
30+ if ( options . w || showAll ) output . push ( wordCount . toString ( ) . padStart ( 8 ) ) ;
31+ if ( options . c || showAll ) output . push ( byteCount . toString ( ) . padStart ( 8 ) ) ;
32+ output . push ( filePath ) ;
33+
34+ console . log ( output . join ( " " ) ) ;
35+ } catch ( err ) {
36+ console . error ( `Error reading file "${ filePath } ":` , err . message ) ;
37+ process . exit ( 1 ) ;
38+ }
You can’t perform that action at this time.
0 commit comments