-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursive-rm.js
More file actions
123 lines (111 loc) · 3.87 KB
/
recursive-rm.js
File metadata and controls
123 lines (111 loc) · 3.87 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
'use strict';
var fs = require('fs');
var path = require('path');
var errors = {
ROOT_PATH_REQUIRED: 1,
UNSAFE_OPERATION: 2,
};
var msgs = {
1: 'RootPath cannot be null under safeDelete mode',
2: 'Danger: Not a valid path for remove operation',
};
function handleError(error) {
console.error(error);
}
module.exports = {
removeDir: function (_path, safeDelete = true, rootPath = null, callback) {
var errorHandle = (callback instanceof Function) ? callback : handleError;
if (safeDelete) {
if (rootPath == null) {
errorHandle({
code: errors.ROOT_PATH_REQUIRED,
Error: msgs[errors.ROOT_PATH_REQUIRED],
});
return;
}
var pathInfo = path.parse(_path);
if (!_path.startsWith(rootPath) || (pathInfo.root === pathInfo.dir && pathInfo.base === '' && pathInfo.name === '')) {
errorHandle({
code: errors.UNSAFE_OPERATION,
Error: msgs[errors.UNSAFE_OPERATION],
});
return;
}
}
var del = function (dir) {
var files = fs.readdirSync(dir);
if(files.length === 0) {
console.info('remove dir', dir);
fs.rmdirSync(dir);
return;
}
files.map(function (file) {
var __path = path.join(dir, file);
var stat = fs.statSync(__path);
if (stat.isFile()) {
console.info(' delete file', __path);
fs.unlinkSync(__path);
} else {
del(__path);
}
});
console.info('remove dir', dir);
fs.rmdirSync(dir);
}
try{
del(_path);
} catch (err) {
errorHandle(err);
}
},
promises: {
removeDir: function (_path, safeDelete = true, rootPath = null) {
return new Promise(function (resolve, reject) {
if (safeDelete) {
if (rootPath == null) {
reject({
code: errors.ROOT_PATH_REQUIRED,
Error: msgs[errors.ROOT_PATH_REQUIRED],
});
return;
}
var pathInfo = path.parse(_path);
if (!_path.startsWith(rootPath) || (pathInfo.root === pathInfo.dir && pathInfo.base === '' && pathInfo.name === '')) {
reject({
code: errors.UNSAFE_OPERATION,
Error: msgs[errors.UNSAFE_OPERATION],
});
return;
}
}
var del = function (dir) {
var files = fs.readdirSync(dir);
if(files.length === 0) {
console.info('remove dir', dir);
fs.rmdirSync(dir);
return;
}
files.map(function (file) {
var __path = path.join(dir, file);
var stat = fs.statSync(__path);
if (stat.isFile()) {
console.info(' delete file', __path);
fs.unlinkSync(__path);
} else {
del(__path);
}
});
console.info('remove dir', dir);
fs.rmdirSync(dir);
}
try{
del(_path);
resolve();
} catch (err) {
reject(err);
}
});
},
},
errors: errors,
};