Created
June 29, 2011 08:04
-
-
Save aseemk/1053383 to your computer and use it in GitHub Desktop.
My implementation of a synchronous `mkdir -p` for Node.
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
# synchronously creates the directory at the given path, including all | |
# intermediate directories, if it doesn't already exist. (like `mkdir -p`) | |
mkdirpSync = (dir) -> | |
# normalize and resolve path to an absolute one: | |
# (path.resolve automatically uses the current directory if needed) | |
dir = path.resolve path.normalize dir | |
# try to create this directory: | |
try | |
# XXX hardcoding recommended file mode of 511 (0777 in octal) | |
# (note that octal numbers are disallowed in ES5 strict mode) | |
fs.mkdirSync dir, 511 | |
# and if we fail, base action based on why we failed: | |
catch e | |
switch e.errno | |
# base case: if the path already exists, we're good to go. | |
# TODO account for this path being a file, not a dir? | |
when constants.EEXIST | |
return | |
# recursive case: some directory in the path doesn't exist, so | |
# make this path's parent directory. | |
when constants.ENOENT | |
mkdirpSync path.dirname dir | |
mkdirpSync dir | |
else | |
throw e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think that may be better...