-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (72 loc) · 1.93 KB
/
index.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
const fs = require('fs')
function getStat (path, callback) {
fs.stat(path, (err, stats) => {
if (err) throw err
callback(stats)
})
}
function readDir (path, callback, errorHandler) {
fs.readdir(path, (err, files) => {
if (err) {
errorHandler()
} else {
callback(files)
}
})
}
function mkDir (path, callback) {
fs.mkdir(path, err => {
if (err) throw err
callback()
})
}
function readAndMkDir (input, output, callback) {
readDir(output, () => {
readDir(input, callback)
}, () => {
mkDir(output, () => {
readDir(input, callback)
})
})
}
function handleFile (input, output, callback) {
fs.readFile(input, (err, res) => {
if (err) throw err
if (callback) {
if (typeof callback !== 'function') throw new Error('callback is not function')
res = callback(res, input, output)
}
fs.writeFile(output, res, err => {
if (err) throw err
})
})
}
function visitDirectory (input, output, inputParent, outputParent, callback) {
const inputPath = inputParent ? inputParent + input : input
const outputPath = outputParent ? outputParent + output : output
getStat(inputPath, stats => {
if (stats.isFile()) {
handleFile(inputPath, outputPath, callback)
} else if (stats.isDirectory()) {
readAndMkDir(inputPath, outputPath, files => {
files.forEach(file => {
if (inputParent) {
visitDirectory(file, file, inputPath + '/', outputPath + '/', callback)
} else {
visitDirectory(file, file, input + '/', output + '/', callback)
}
})
})
}
})
}
function copyFiles (input, output, callback) {
const baseInput = /\/$/.test(input)
? input.substring(0, input.length - 1)
: input
const baseOutput = /\/$/.test(output)
? output.substring(0, output.length - 1)
: output
visitDirectory(baseInput, baseOutput, '', '', callback)
}
module.exports = copyFiles