| 1 |
"use strict"; |
| 2 |
|
| 3 |
const fs = require("fs") |
| 4 |
, path = require("path") |
| 5 |
, ensureString = require("type/string/ensure") |
| 6 |
, isObject = require("type/object/is") |
| 7 |
, toShortString = require("type/lib/to-short-string"); |
| 8 |
|
| 9 |
const emptyDirSync = (dirname, options) => { |
| 10 |
let errors; |
| 11 |
for (const basename of fs.readdirSync(dirname)) { |
| 12 |
const filename = path.resolve(dirname, basename); |
| 13 |
try { |
| 14 |
const stats = fs.statSync(filename); |
| 15 |
if (stats.isDirectory()) { |
| 16 |
if (options.recursive) emptyDirSync(filename, options); |
| 17 |
rmDirSync(filename); |
| 18 |
} else { |
| 19 |
fs.unlinkSync(filename); |
| 20 |
} |
| 21 |
} catch (error) { |
| 22 |
if (!errors) errors = []; |
| 23 |
if (error.errors) errors.push(...error.errors); |
| 24 |
else errors.push(Object.assign(error, { _filename: filename })); |
| 25 |
} |
| 26 |
} |
| 27 |
if (errors) { |
| 28 |
throw Object.assign(new Error("Could not empty dir"), { errors }); |
| 29 |
} |
| 30 |
}; |
| 31 |
|
| 32 |
module.exports = (dirnameInput, options = {}) => { |
| 33 |
const dirname = path.resolve(ensureString(dirnameInput)); |
| 34 |
if (!isObject(options)) options = {}; |
| 35 |
try { |
| 36 |
emptyDirSync(dirname, options); |
| 37 |
} catch (error) { |
| 38 |
if (!error.errors) throw error; |
| 39 |
let errorMessage = `Could not remove ${ toShortString(dirnameInput) } due to:\n- ${ |
| 40 |
error.errors.slice(0, 5).map(({ code, _filename }) => `${ code } on ${ _filename }`) |
| 41 |
}`; |
| 42 |
if (error.errors.length > 5) { |
| 43 |
errorMessage += `\nand ${ error.errors.length - 5 } other errors`; |
| 44 |
} |
| 45 |
throw Object.assign(new Error(errorMessage), { errors: error.errors }); |
| 46 |
} |
| 47 |
}; |
| 48 |
|
| 49 |
const rmDirSync = require("./rmdir-sync"); |