File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ const fs = require ( "fs" ) ;
2+
3+ const args = process . argv . slice ( 2 ) ;
4+
5+ let countLines = false ;
6+ let countWords = false ;
7+ let countBytes = false ;
8+ let files = [ ] ;
9+
10+ for ( const arg of args ) {
11+ if ( arg === "-l" ) {
12+ countLines = true ;
13+ } else if ( arg === "-w" ) {
14+ countWords = true ;
15+ } else if ( arg === "-c" ) {
16+ countBytes = true ;
17+ } else {
18+ files . push ( arg ) ;
19+ }
20+ }
21+
22+ // If no flags are given, wc shows all three
23+ if ( ! countLines && ! countWords && ! countBytes ) {
24+ countLines = true ;
25+ countWords = true ;
26+ countBytes = true ;
27+ }
28+
29+ function countFile ( filename ) {
30+ const content = fs . readFileSync ( filename , "utf8" ) ;
31+
32+ const lines = content . split ( "\n" ) . length - 1 ;
33+ const words = content . trim ( ) === "" ? 0 : content . trim ( ) . split ( / \s + / ) . length ;
34+ const bytes = Buffer . byteLength ( content ) ;
35+
36+ let output = [ ] ;
37+
38+ if ( countLines ) {
39+ output . push ( lines ) ;
40+ }
41+
42+ if ( countWords ) {
43+ output . push ( words ) ;
44+ }
45+
46+ if ( countBytes ) {
47+ output . push ( bytes ) ;
48+ }
49+
50+ output . push ( filename ) ;
51+
52+ console . log ( output . join ( " " ) ) ;
53+ }
54+
55+ for ( const file of files ) {
56+ countFile ( file ) ;
57+ }
You can’t perform that action at this time.
0 commit comments