1
+ import fs from 'fs' ;
2
+ import path from 'path' ;
3
+ import { fileURLToPath } from 'url' ;
4
+ const __filename = fileURLToPath ( import . meta. url ) ;
5
+ const __dirname = path . dirname ( __filename ) ;
6
+
7
+ function concatFiles ( dest , cb , ...srcFiles ) {
8
+ const startIndex = 0 ;
9
+ const initialContent = '' ;
10
+
11
+ readfiles ( srcFiles , startIndex , initialContent , ( err , data ) => {
12
+ if ( err ) return cb ( err ) ;
13
+ fs . writeFile ( dest , data , cb ) ;
14
+ } )
15
+ }
16
+
17
+ function readfiles ( srcFiles , index , content , cb ) {
18
+ if ( index === srcFiles . length ) return cb ( null , content ) ;
19
+
20
+ return fs . readFile ( srcFiles [ index ] , ( err , data ) => {
21
+ if ( err ) return cb ( err ) ;
22
+ // read next file recursively
23
+ readfiles ( srcFiles , index + 1 , content + data , cb ) ;
24
+ } ) ;
25
+ }
26
+
27
+ // test
28
+ const srcFiles = [ 'file0.txt' , 'file1.txt' , 'file2.txt' , 'file3.txt' , 'file4.txt' ]
29
+ . map ( fileName => path . join ( __dirname , fileName ) ) ;
30
+ const dest = path . join ( __dirname , 'result.txt' ) ;
31
+
32
+ concatFiles ( dest , ( err , data ) => {
33
+ if ( err ) return console . log ( 'Error occured' , err ) ;
34
+ console . log ( 'Written to file' , dest ) ;
35
+ } , ...srcFiles )
0 commit comments