-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4.1-concat-files.js
129 lines (97 loc) · 2.66 KB
/
4.1-concat-files.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import fs from 'fs'
function readFile(filePath, cb) {
fs.access(filePath, err1 => {
if (err1) {
return cb(err1)
}
fs.readFile(filePath, 'utf-8', (err2, fileContent) => {
if (err2) {
return cb(err2)
}
cb(null, fileContent)
})
})
}
function concatFiles() {
const args = Array.from(arguments)
if (!args.length) {
throw new Error('Not enough arguments! Expected at least three arguments (callback, dest, srcFile1, srcFile2, ..., srcFilen)')
}
const [cb, dest, ...src] = args
if (typeof cb !== 'function') {
throw new Error('Last argument needs to be a function')
}
if (typeof dest !== 'string') {
throw new Error('Before last argument needs to be a string representing destination path')
}
if (!src.length) {
throw new Error('Need at least one source file!')
}
if (src.some(source => typeof source !== 'string')) {
throw new Error('All source files needs to be of type string!')
}
let finalText = ''
function iterate(index) {
if (index === src.length) {
return cb(null, finalText, dest)
}
readFile(src[index], (err, textContent) => {
if (err) {
return cb(err)
}
finalText = `${finalText}${textContent}`
iterate(index + 1)
})
}
readFile(dest, (err, fileContent) => {
if (err) {
return cb(err)
}
finalText = fileContent
iterate(0)
})
}
concatFiles(
(err, finalText, dest) => {
if (err) {
return console.error(err)
}
fs.writeFile(dest, finalText, writeErr => {
if (writeErr) {
return console.error(writeErr)
}
console.log(`${finalText} has been written to ${dest}`)
})
},
'./filesToConcat/dest.txt',
'./filesToConcat/foo.txt',
'./filesToConcat/bar.txt',
'./filesToConcat/baz.txt',
)
// import path from 'path'
function concatFilesOld(srcFiles, dest, cb) {
let finalText = ''
function iterate(index) {
if (index === srcFiles.length) {
return cb(null, finalText)
}
readFile(srcFiles[index], (err, data) => {
if (err) {
return cb(err)
}
// append text to final text
finalText = `
${finalText}
${data}
`
iterate(index + 1)
})
}
readFile(dest, (err1, initialText) => {
if (err1) {
return cb(err1)
}
finalText = initialText
iterate(0)
})
}