-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
63 lines (58 loc) · 1.83 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
/* SOURCE FILE - Copyright (c) 2018 rm-dir - Tanase Laurentiu Iulian - https://github.com/RealTimeCom/rm-dir */
'use strict';
const fs = require('fs'),
s = require('path').sep;
function each(d, a, cb) {
if (typeof cb === 'function') { // async
if (a.length > 0) {
fs.unlink(d + s + a[0], e => {
if (e) {
if (e.code === 'EISDIR') {
rmdir(d + s + a[0], e => {
if (e) { cb(e); } else { each(d, a.splice(0, 1) ? a : a, cb); }
});
} else { cb(e); }
} else { each(d, a.splice(0, 1) ? a : a, cb); }
});
} else { fs.rmdir(d, cb); }
} else { // sync
if (a.length > 0) {
try {
fs.unlinkSync(d + s + a[0]);
each(d, a.splice(0, 1) ? a : a);
} catch (e) {
if (e.code === 'EISDIR') {
rmdir(d + s + a[0]);
each(d, a.splice(0, 1) ? a : a);
} else { throw e; }
}
} else { fs.rmdirSync(d); }
}
}
function rmdir(d, cb) {
if (typeof cb === 'function') { // async
fs.rmdir(d, e => {
if (e) {
if (e.code === 'ENOTEMPTY') {
fs.readdir(d, (e, a) => {
if (e) { cb(e); } else { each(d, a, cb); }
});
} else { cb(e); }
} else { cb(); }
});
} else { // sync
try {
fs.rmdirSync(d);
} catch (e) {
if (e.code === 'ENOTEMPTY') {
each(d, fs.readdirSync(d));
} else { throw e; }
}
}
}
rmdir.promise = d => new Promise((res, rej) => {
rmdir(d, e => {
e ? rej(e) : res(null);
});
});
module.exports = rmdir;