forked from RajeshkannanRamakrishnan/desktop-avatar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.js
56 lines (51 loc) · 1.35 KB
/
util.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
'use strict'
const fs = require('fs')
const path = require('path')
/* outcome/
* Create the folders in the path by creating each path in turn
*/
function ensureExists(path_, cb) {
try {
path_ = path.normalize(path_)
} catch(err) {
return cb(err)
}
let p = path_.split(path.sep)
if(p[0] == '.') p.shift() // Don't create current directory
else if(p[0] == '') { // Absolute path
p.shift()
p[0] = path.sep + p[0]
}
ensure_exists_1(p, 1)
function ensure_exists_1(p, upto) {
if(p.length < upto) cb(null, path_)
else {
let curr = path.join.apply(path, p.slice(0,upto))
fs.mkdir(curr, '0777', (err) => {
if (err && err.code != 'EEXIST' && err.code != 'EPERM') cb(err)
else ensure_exists_1(p, upto+1)
})
}
}
}
/* understand/
* given a name - try and make it as 'clean' as possible
* so it's usable as a filename
*/
function sanitizeFilename(n) {
let illegalRe = /[\/\?<>\\:\*\|"]/g;
let controlRe = /[\x00-\x1f\x80-\x9f]/g;
let reservedRe = /^\.+$/;
let windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;
let windowsTrailingRe = /[\. ]+$/
return n
.replace(illegalRe, '')
.replace(controlRe, '')
.replace(reservedRe, '')
.replace(windowsReservedRe, '')
.replace(windowsTrailingRe, '')
}
module.exports = {
ensureExists,
sanitizeFilename,
}