11import { program } from "commander" ;
2- import { error } from "node:console" ;
3- import { promises as fs , link } from "node:fs" ;
2+
3+ import { promises as fs } from "node:fs" ;
44
55program
66 . name ( "wc" )
77 . description ( "wc implementation" )
8- . argument ( "<paths...>" , "the file path to process" ) ;
8+ . argument ( "<paths...>" , "the file path to process" )
9+ . option ( "-l" , "count how many lines" ) ;
910program . parse ( ) ;
1011
12+
1113const paths = program . args ;
14+
15+ if ( paths . length === 0 ) {
16+ console . error ( "Expected at least one argument (a path)" ) ;
17+ process . exit ( 1 ) ;
18+ }
19+
20+
21+ const options = program . opts ( ) ;
1222const total = {
1323 linesCounter : 0 ,
1424 wordsCounter : 0 ,
1525 characterCounter : 0 ,
1626} ;
17- try {
18- for ( const path of paths ) {
19- const content = await fs . readFile ( path , "utf-8" ) ;
27+ try {
28+ for ( const path of paths ) {
29+ const content = await fs . readFile ( path , "utf-8" ) ;
2030
21- const linesCounter = content . split ( "\n" ) . length - 1 ;
22- const wordsCounter = content . trim ( ) . split ( / \s + / ) . length ;
23- const characterCounter = content . length ;
31+ const linesCounter = content . split ( "\n" ) . length - 1 ;
32+ const wordsCounter = content . trim ( ) . split ( / \s + / ) . length ;
33+ const characterCounter = content . length ;
2434
25- total . linesCounter += linesCounter ;
26- total . wordsCounter += wordsCounter ;
27- total . characterCounter += characterCounter ;
35+ total . linesCounter += linesCounter ;
36+ total . wordsCounter += wordsCounter ;
37+ total . characterCounter += characterCounter ;
2838
29- console . log ( ` ${ linesCounter } ${ wordsCounter } ${ characterCounter } ${ path } ` ) ;
39+ if ( options . l ) {
40+ console . log ( `${ linesCounter } ${ path } ` ) ;
41+ } else {
42+ console . log (
43+ ` ${ linesCounter } ${ wordsCounter } ${ characterCounter } ${ path } ` ,
44+ ) ;
45+ }
46+ }
47+ if ( paths . length > 1 ) {
48+ if ( options . l ) {
49+ console . log ( `${ total . linesCounter } total` ) ;
50+ } else {
51+ console . log (
52+ ` ${ total . linesCounter } ${ total . wordsCounter } ${ total . characterCounter } total` ,
53+ ) ;
54+ }
55+ }
56+ } catch ( error ) {
57+ console . error ( error . message ) ;
3058}
31- if ( paths . length > 1 )
32- console . log (
33- ` ${ total . linesCounter } ${ total . wordsCounter } ${ total . characterCounter } total` ,
34- ) ;
35- } catch ( error ) {
36- console . log ( error . message ) ;
37- }
0 commit comments