Created
December 27, 2014 09:42
-
-
Save dead-claudia/0429706da643000e6657 to your computer and use it in GitHub Desktop.
Recursive rmdir inspired by CoffeeScript implementation from https://gist.github.com/4605986
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
require! {fs, path} | |
# Promises simplify things greatly here. This, by default, uses an ES6 | |
# polyfill if a global Promise doesn't exist (either already implemented or | |
# polyfilled by something else) | |
if typeof Promise == 'undefined' | |
require! 'es6-promise': {Promise} | |
# For other promise libraries... | |
#require! 'Bluebird': Promise | |
#require! 'rsvp': {all, Promise}; Promise.all = all | |
# etc. | |
# Functional convenience | |
map = (f, xs) --> [f x for x in xs] | |
promisify = (f) -> (...args) -> | |
new Promise (resolve, reject) -> | |
f ...args, (err, data) -> | |
| err? => reject err | |
| otherwise => resolve data | |
stat = promisify fs.stat | |
unlink = promisify fs.unlink | |
readdir = promisify fs.readdir | |
rmdir1 = promisify fs.rmdir # renamed to avoid clash with export | |
unlinkEntry = (file) -> | |
stat file .then (stat) -> | |
| stat.isDirectory! => rmdir2 file # Remove recursively | |
| otherwise => unlink file # Unlink this file | |
rmdir = (dir) -> | |
readdir dir | |
.then Promise.all unlinkEntry map (path.join dir, _) | |
.then rmdir1 dir | |
module.exports = rmdir = (dir, cb) !-> | |
# We want both sides immediately handled. Also, it's simpler this way. | |
rmdir2 dir .then (-> cb null), (-> cb it) |
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
require! {fs, path} | |
# Functional conveniences | |
map = (f, xs) --> [f x for x in xs] | |
each = (f, xs) !--> for x in xs => f x | |
module.exports = rmdir = (dir) !-> | |
fs.readdirSync dir | |
|> each (-> path.join dir, it) >> (file) !-> | |
| fs.statSync file .isDirectory! => rmdir file # Remove recursively | |
| otherwise => fs.unlink file # Unlink this file | |
fs.rmdirSync dir # Finally remove the file |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment