-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReplacer.js
More file actions
58 lines (50 loc) · 1.45 KB
/
Replacer.js
File metadata and controls
58 lines (50 loc) · 1.45 KB
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
const fs = require('fs')
const blackList = ['.DS_Store']
const replace = (path, transformMap) => {
fs.readFile(path, 'utf8', (err, data) => {
if (err) {
console.err(`Could not read file from ${path}`)
throw err
} else {
let result = data
Object.keys(transformMap).forEach(
key =>
(result = result.replace(new RegExp(key, 'g'), transformMap[key]))
)
fs.writeFileSync(path, result, 'utf8', err => {
if (err) {
console.err(`Could not write result to ${path}`)
throw err
}
})
}
})
}
const filesInDirectory = dir => {
return traversable(fs.readdirSync(dir))
.filter(path => fs.lstatSync(`${dir}/${path}`).isFile())
.map(file => `${dir}/${file}`)
}
const directoriesInDirectory = dir => {
return traversable(fs.readdirSync(dir))
.filter(path => fs.lstatSync(dir + '/' + path).isDirectory())
.map(folder => dir + '/' + folder)
}
const traversable = (directories, blacklist = blackList) => {
return directories.filter(dir => !blackList.includes(dir))
}
const findAllFiles = dir => {
let files = filesInDirectory(dir)
const directories = directoriesInDirectory(dir)
for (directory of directories) {
files = [...files, ...findAllFiles(directory)]
}
return files
}
const replaceInFiles = (path, transformMap) => {
const files = findAllFiles(path)
for (file of files) {
replace(file, transformMap)
}
}
module.exports = replaceInFiles