Skip to content

Instantly share code, notes, and snippets.

@bpedro
Last active October 31, 2020 00:35
Show Gist options
  • Save bpedro/742162 to your computer and use it in GitHub Desktop.
Save bpedro/742162 to your computer and use it in GitHub Desktop.
nodejs implementation of recursive directory creation (https://brunopedro.com/2010/12/15/recursive-directory-nodejs/)
var fs = require('fs');
/**
* Offers functionality similar to mkdir -p
*
* Asynchronous operation. No arguments other than a possible exception
* are given to the completion callback.
*/
function mkdir_p(path, mode, callback, position) {
mode = mode || 0777;
position = position || 0;
parts = require('path').normalize(path).split('/');
if (position >= parts.length) {
if (callback) {
return callback();
} else {
return true;
}
}
var directory = parts.slice(0, position + 1).join('/');
fs.stat(directory, function(err) {
if (err === null) {
mkdir_p(path, mode, callback, position + 1);
} else {
fs.mkdir(directory, mode, function (err) {
if (err) {
if (callback) {
return callback(err);
} else {
throw err;
}
} else {
mkdir_p(path, mode, callback, position + 1);
}
})
}
})
}
@crackcomm
Copy link

path = require 'path'
fs   = require 'fs'

mkdirtree = (path, cb, pos=0) ->

  tree = path.split '/'

  if pos is tree.length
    return cb null, path

  dir = tree.slice(0, pos+1).join '/'

  next = ->
    mkdirtree path, cb, pos+1

  if tree[pos] is ''
    next()
  else
    fs.exists dir, (exists) ->
      if exists then next()
      else
        fs.mkdir dir, (err) ->
          if err then cb err
          else next()

My CoffeeScript code.
I was using Your code for fast prototype, here is my fully functional (I think) coffeescript code.

@wilensky
Copy link

wilensky commented Jan 3, 2015

Small code block using fs.mkdirSync().
Original gist here.

var fs = require('fs');

/**
 * Splits whole path into segments and checks each segment for existence and recreates directory tree from the bottom.
 * If since some segment tree doesn't exist it will be created in series.
 * Existing directories will be skipped.
 * @param {String} directory
 */
function mkdirSyncRecursive(directory) {
    var path = directory.replace(/\/$/, '').split('/');

    for (var i = 1; i <= path.length; i++) {
        var segment = path.slice(0, i).join('/');
        !fs.existsSync(segment) ? fs.mkdirSync(segment) : null ;
    }
}

@jaywcjlove
Copy link

function mkdirs(dirPath, mode, callback) {
    //Call the standard fs.mkdir
    fs.mkdir(dirPath, mode, function(error) {
        //When it fail in this way, do the custom steps
        if (error && error.errno === 34) {
            //Create all the parents recursively
            mkdirs(path.dirname(dirPath), mode, callback);
            //And then the directory
            mkdirs(dirPath, mode, callback);
        }
        //Manually run the callback since we used our own callback to do all these
        !error&&callback && callback(error);
    });
};

@BenjaminVanRyseghem
Copy link

another implementation using the latest fs & path

function mkdir(dir) {
    // we explicitly don't use `path.sep` to have it platform independent;
    var sep = '/';

    var segments = dir.split(sep);
    var current = '';
    var i = 0;

    while (i < segments.length) {
        current = current + sep + segments[i];
        try {
            fs.statSync(current);
        } catch (e) {
            fs.mkdirSync(current);
        }

        i++;
    }
}

@irudoy
Copy link

irudoy commented Jun 1, 2018

const path = require('path');
const fs = require('fs');

const mkdirp = dir => path
    .resolve(dir)
    .split(path.sep)
    .reduce((acc, cur) => {
        const currentPath = path.normalize(acc + path.sep + cur);
        try {
            fs.statSync(currentPath);
        } catch (e) {
            if (e.code === 'ENOENT') {
                fs.mkdirSync(currentPath);
            } else {
                throw e;
            }
        }
        return currentPath;
    }, '');

@sabicalija
Copy link

sabicalija commented Jan 28, 2019

const path = require("path");
const fs = require("fs");

function mkdirp(directory) {
  if (!path.isAbsolute(directory)) return;
  let parent = path.join(directory, "..");
  if (parent !== path.join("/") && !fs.existsSync(parent)) mkdirp(parent);
  if (!fs.existsSync(directory)) fs.mkdirSync(directory);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment