1+ import process from "node:process" ;
2+ import { program } from "commander" ;
3+ import { promises as fs } from "node:fs" ;
4+
5+ program
6+ . name ( "WC clone" )
7+ . description ( "Counting each words in a given file" )
8+ . argument ( "<files...>" , "one or more files to count the words" )
9+ . action ( async ( files ) => {
10+ let totalLines = 0 ;
11+ let totalWords = 0 ;
12+ let totalBytes = 0 ;
13+
14+ for ( const file of files ) {
15+ try {
16+ const content = await fs . readFile ( file , "utf-8" ) ;
17+ const size = await fs . readFile ( file ) ;
18+
19+ const lineCount = content . split ( "\n" ) . length - 1 ;
20+
21+ const wordCount = content . trim ( ) === "" ? 0 : content . trim ( ) . split ( / \s + / ) . length ;
22+
23+ const byteCount = size . length ;
24+
25+ totalLines += lineCount ;
26+ totalWords += wordCount ;
27+ totalBytes += byteCount ;
28+
29+ printCounts ( { lineCount, wordCount, byteCount, label :file , } ) ;
30+ }
31+
32+ catch ( err ) {
33+ console . error ( "No such file or directory" ) ;
34+ process . exit ( 1 ) ;
35+ }
36+ }
37+
38+ if ( files . length > 1 )
39+ {
40+ printCounts ( { lineCount :totalLines ,
41+ wordCount :totalWords ,
42+ byteCount :totalBytes ,
43+ label :"Total" ,
44+ } )
45+ }
46+
47+ } ) ;
48+
49+ function printCounts ( { lineCount, wordCount, byteCount, label} )
50+ {
51+ let output = "" ;
52+
53+ output += lineCount . toString ( ) . padStart ( 7 , " " ) ;
54+ output += wordCount . toString ( ) . padStart ( 7 , " " ) ;
55+ output += byteCount . toString ( ) . padStart ( 7 , " " ) ;
56+
57+ console . log ( `${ output } ${ label } ` ) ;
58+ }
59+
60+ program . parse ( process . argv ) ;
0 commit comments