Skip to content

Instantly share code, notes, and snippets.

@dead-claudia
Created December 27, 2014 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dead-claudia/0429706da643000e6657 to your computer and use it in GitHub Desktop.
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
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)
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