1+ import process from "node:process" ;
2+ import { promises as fs } from "node:fs" ;
3+
4+ const argv = process . argv . slice ( 2 , process . argv . length ) ;
5+ let flag = '' ;
6+ const paths = [ ] ;
7+ let dir = '' ;
8+ let ending = '' ;
9+ for ( let i = 0 ; i < argv . length ; i ++ ) {
10+ if ( argv [ i ] [ 0 ] == "-" ) {
11+ flag = argv [ i ] ;
12+ } else {
13+ paths . push ( argv [ i ] ) ;
14+ }
15+ }
16+
17+ if ( paths . length > 0 ) {
18+ dir = paths [ 0 ] . slice ( 0 , paths [ 0 ] . indexOf ( "/" ) ) ;
19+ ending = paths [ 0 ] . slice ( paths [ 0 ] . indexOf ( "/" ) + 1 ) ;
20+ } ;
21+
22+ const files = await resolveQuery ( paths , dir , ending ) ;
23+ await logFilesInfo ( files , flag ) ;
24+
25+ async function resolveQuery ( paths , dir , ending ) {
26+ let files = [ ] ;
27+ if ( paths . length > 1 ) {
28+ files = await fs . readdir ( dir ) ;
29+ } else {
30+ files = [ ending ] ;
31+ }
32+ return files ;
33+ }
34+
35+ async function logFilesInfo ( files , flag ) {
36+ let totalLines = 0 ;
37+ let totalWords = 0 ;
38+ let totalBytes = 0 ;
39+ let totalOutput = '' ;
40+ for ( const fileName of files ) {
41+ let fileOutput = '' ;
42+ let filePath = dir + "/" + fileName ;
43+ let file = await fs . readFile ( filePath , "utf-8" ) ;
44+ let linesNum = countLinesInString ( file ) ;
45+ let wordsNum = countWordsInString ( file ) ;
46+ let bytes = file . length ;
47+ totalLines += linesNum ;
48+ totalWords += wordsNum ;
49+ totalBytes += bytes ;
50+ if ( flag == "-l" ) {
51+ fileOutput = linesNum + " " + filePath ;
52+ } else if ( flag == "-w" ) {
53+ fileOutput = wordsNum + " " + filePath ;
54+ } else if ( flag == '-c' ) {
55+ fileOutput = bytes + " " + filePath ;
56+ } else {
57+ fileOutput = linesNum + " " + wordsNum + " " + bytes + " " + filePath ;
58+ }
59+ console . log ( fileOutput ) ;
60+ }
61+ if ( files . length > 1 ) {
62+ if ( flag == "-l" ) {
63+ totalOutput = totalLines + " total" ;
64+ } else if ( flag == "-w" ) {
65+ totalOutput = totalWords + " total" ;
66+ } else if ( flag == '-c' ) {
67+ totalOutput = totalBytes + " total" ;
68+ } else {
69+ totalOutput = totalLines + " " + totalWords + " " + totalBytes + " total" ;
70+ }
71+ console . log ( totalOutput ) ;
72+ }
73+ }
74+
75+ function countLinesInString ( str ) {
76+ let lines = str . split ( '\n' ) ;
77+ let linesNum = lines . length ;
78+ if ( lines [ lines . length - 1 ] == '' ) {
79+ linesNum -- ;
80+ }
81+ return linesNum ;
82+ }
83+
84+ function countWordsInString ( str ) {
85+ let words = str . replace ( / \n / g, ' ' ) . split ( ' ' ) ;
86+ words = words . filter ( ( word ) => {
87+ return ( word != '' )
88+ } ) ;
89+ let wordsNum = words . length ;
90+ return wordsNum ;
91+ }
0 commit comments