File tree Expand file tree Collapse file tree
implement-shell-tools/cat Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import { promises as fs } from "node:fs" ;
2+ import process from "node:process" ;
3+
4+ const args = process . argv . slice ( 2 ) ;
5+
6+ if ( args . length === 0 ) {
7+ console . error ( "Usage: node cat.js [-n] [-b] <file...>" ) ;
8+ process . exit ( 1 ) ;
9+ }
10+ const showAllLineNumbers = args . includes ( "-n" ) ;
11+ const showNonBlankNumbers = args . includes ( "-b" ) ;
12+
13+ const filePaths = args . filter ( ( arg ) => ! arg . startsWith ( "-" ) ) ;
14+
15+ let lineNumber = 1 ;
16+
17+ for ( const filePath of filePaths ) {
18+ const content = await fs . readFile ( filePath , "utf-8" ) ;
19+
20+ if ( ! showAllLineNumbers && ! showNonBlankNumbers ) {
21+ process . stdout . write ( content ) ;
22+ } else {
23+ const lines = content . split ( "\n" ) ;
24+
25+ for ( let i = 0 ; i < lines . length ; i ++ ) {
26+ const line = lines [ i ] ;
27+
28+ let isLastLine ;
29+ if ( i === lines . length - 1 ) {
30+ isLastLine = true ;
31+ } else {
32+ isLastLine = false ;
33+ }
34+
35+ if ( isLastLine && line === "" ) {
36+ break ;
37+ }
38+
39+ if ( showAllLineNumbers ) {
40+ const paddedNumber = String ( lineNumber ) . padStart ( 6 , " " ) ;
41+ process . stdout . write ( `${ paddedNumber } \t${ line } \n` ) ;
42+ lineNumber ++ ;
43+ } else if ( showNonBlankNumbers ) {
44+ if ( line . trim ( ) === "" ) {
45+ process . stdout . write ( "\n" ) ;
46+ } else {
47+ const paddedNumber = String ( lineNumber ) . padStart ( 6 , " " ) ;
48+ process . stdout . write ( `${ paddedNumber } \t${ line } \n` ) ;
49+ lineNumber ++ ;
50+ }
51+ }
52+ }
53+ }
54+ }
Original file line number Diff line number Diff line change 1+ {
2+ "type" : " module"
3+ }
You can’t perform that action at this time.
0 commit comments