Skip to content

Commit 8dc941b

Browse files
committed
Add 4.1 solution
1 parent a978d31 commit 8dc941b

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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

Comments
 (0)