/
index.js
53 lines (47 loc) · 1.46 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
const fs = require("fs");
const util = require("util");
const assert = require("assert");
const glob = require("glob");
const statPro = util.promisify(fs.stat);
const unlinkPro = util.promisify(fs.unlink);
const readdirPro = util.promisify(fs.readdir);
const rmdirPro = util.promisify(fs.rmdir);
const globPro = util.promisify(glob);
const _rmrf = async function(p, opt) {
let stat;
try {
stat = await statPro(p);
} catch (e) {
if (e.code === "ENOENT") return;
else console.log(e);
}
if (!stat.isDirectory()) {
if (opt.log) console.log(`rm ${p}`);
await unlinkPro(p);
} else {
const files = await readdirPro(p);
for (const file of files) {
const path = `${p}/${file}`;
await _rmrf(path, opt);
}
if (opt.log) console.log(`rm ${p}`);
await rmdirPro(p);
}
};
const OPT = {log: true}
module.exports = async function rmrf(path, opt = OPT, cb = _ => {}) {
if(typeof opt === 'function') {
cb = opt;
opt = OPT
}
assert(path, 'need path');
assert.equal(typeof path, 'string', 'path should be a string');
assert.equal(Object.prototype.toString.call(opt), '[object Object]', 'path should be a object');
assert.equal(typeof cb, 'function', 'callback sholud be a function');
return globPro(path).then(async files => {
for(let file of files) {
await _rmrf(file, opt);
}
cb && cb();
});
}