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);
}
})
}
})
}
@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