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+ #!/usr/bin/env node
2+
3+ const fs = require ( 'fs' ) ;
4+ const path = require ( 'path' ) ;
5+
6+ function cat ( files , options ) {
7+ let lineNumber = 1 ;
8+
9+ files . forEach ( ( file ) => {
10+ const filePath = path . resolve ( file ) ;
11+
12+ try {
13+ const data = fs . readFileSync ( filePath , 'utf8' ) ;
14+ const lines = data . split ( '\n' ) ;
15+
16+ lines . forEach ( ( line ) => {
17+ if ( options . numberNonEmpty && line . trim ( ) ) {
18+ console . log ( `${ lineNumber } \t${ line } ` ) ;
19+ lineNumber ++ ;
20+ } else if ( options . numberLines ) {
21+ console . log ( `${ lineNumber } \t${ line } ` ) ;
22+ lineNumber ++ ;
23+ } else {
24+ console . log ( line ) ;
25+ }
26+ } ) ;
27+ } catch ( err ) {
28+ console . error ( `cat: ${ file } : No such file or directory` ) ;
29+ }
30+ } ) ;
31+ }
32+
33+ function main ( ) {
34+ const args = process . argv . slice ( 2 ) ;
35+ const options = {
36+ numberLines : false ,
37+ numberNonEmpty : false ,
38+ } ;
39+
40+ const files = [ ] ;
41+
42+ args . forEach ( ( arg ) => {
43+ if ( arg === '-n' ) {
44+ options . numberLines = true ;
45+ } else if ( arg === '-b' ) {
46+ options . numberNonEmpty = true ;
47+ } else {
48+ files . push ( arg ) ;
49+ }
50+ } ) ;
51+
52+ if ( files . length === 0 ) {
53+ console . error ( 'Usage: node cat.js [-n | -b] <file>...' ) ;
54+ process . exit ( 1 ) ;
55+ }
56+
57+ cat ( files , options ) ;
58+ }
59+
60+ main ( ) ;
You can’t perform that action at this time.
0 commit comments