11import { promises as fs } from "node:fs" ;
2- // import path from "node:path";
32import { program } from "commander" ;
4- import { clearLine } from "node:readline" ;
53
64program
75 . name ( "cat" )
@@ -15,26 +13,36 @@ const argv = program.args;
1513
1614const opts = program . opts ( ) ;
1715
18- const flag_n = ( data ) => {
19- const numberOfLines = data . split ( "\n" ) . length - 1 ;
20- return numberOfLines ;
16+ const countLines = ( data ) => {
17+ const lines = data . split ( "\n" ) ;
18+ if ( lines [ lines . length - 1 ] === "" ) {
19+ lines . pop ( ) ;
20+ }
21+
22+ let lineNum = 1 ;
23+
24+ for ( const line of lines ) {
25+ if ( opts . b ) {
26+ if ( line . trim ( ) === "" ) {
27+ console . log ( ) ;
28+ } else {
29+ console . log ( `${ lineNum } ${ line } ` ) ;
30+ lineNum ++ ;
31+ }
32+ } else if ( opts . n ) {
33+ console . log ( `${ lineNum } ${ line } ` ) ;
34+ lineNum ++ ;
35+ }
36+ }
2137} ;
22- let number = 0 ;
38+
2339async function example ( path ) {
2440 try {
2541 const data = await fs . readFile ( path , { encoding : "utf8" } ) ;
26- if ( opts [ "n" ] ) {
27- const lines = data . split ( "\n" ) ;
28- if ( lines [ lines . length - 1 ] === "" ) {
29- lines . pop ( ) ;
30- }
31-
32- for ( let i = 0 ; i < lines . length ; i ++ ) {
33- const line = lines [ i ] ;
34- const output = `${ number + 1 } ${ line } ` ;
35- number += 1 ;
36- console . log ( output . trimEnd ( ) ) ;
37- }
42+ if ( opts [ "b" ] ) {
43+ countLines ( data ) ;
44+ } else if ( opts [ "n" ] ) {
45+ countLines ( data ) ;
3846 } else {
3947 console . log ( data . trimEnd ( ) ) ;
4048 }
@@ -50,6 +58,3 @@ const handleInput = async () => {
5058} ;
5159
5260handleInput ( ) ;
53- // for (const path of argv) {
54- // example(path);
55- // }
0 commit comments