Created
March 30, 2018 10:23
-
-
Save AnatoliyLitinskiy/6f1a815764ff60a08f52cf9b2b256001 to your computer and use it in GitHub Desktop.
remove / clean out directory using node.js fs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const path = require('path'); | |
const async = require('async'); | |
function rmDir(dirPath, cb, removeSelf = true) { | |
try { | |
fs.readdir(dirPath, (err, files) => { | |
if (err) return cb(err); | |
// run tasks in parallel | |
async.each(files, (file, cb) => { | |
try { | |
const filePath = path.join(dirPath, file); | |
fs.stat(filePath, (err, stats) => { | |
if (err) return cb(err); | |
if (stats.isFile()) { | |
fs.unlink(filePath, cb); | |
} else { | |
rmDir(filePath, cb); | |
} | |
}); | |
} catch (err) { | |
cb(err); | |
}; | |
}, (err) => { | |
if (err) return cb(err); | |
if (removeSelf) { | |
fs.rmdir(dirPath, cb); | |
} else { | |
cb(); | |
} | |
}); | |
}); | |
} catch(e) { | |
cb(e); | |
} | |
}; | |
const cleanDir = (dirPath, cb) => rmDir(dirPath, cb, false); | |
module.exports = { | |
rmDir, | |
cleanDir, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment