-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
nodeUtils.js
33 lines (29 loc) · 931 Bytes
/
nodeUtils.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
import fs from 'fs'
export function writeFileSyncRecursive(filename, content, charset) {
// -- normalize path separator to '/' instead of path.sep,
// -- as / works in node for Windows as well, and mixed \\ and / can appear in the path
let filepath = filename.replace(/\\/g, '/')
// -- preparation to allow absolute paths as well
let root = ''
if (filepath[0] === '/') {
root = '/'
filepath = filepath.slice(1)
} else if (filepath[1] === ':') {
root = filepath.slice(0, 3) // c:\
filepath = filepath.slice(3)
}
// -- create folders all the way down
const folders = filepath.split('/').slice(0, -1) // remove last item, file
folders.reduce(
(acc, folder) => {
const folderPath = acc + folder + '/'
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath)
}
return folderPath
},
root // first 'acc', important
)
// -- write file
fs.writeFileSync(root + filepath, content, charset)
}