Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fs.mkdir(sync) supports recursive option #55

Merged
merged 2 commits into from Apr 24, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
46 changes: 6 additions & 40 deletions lib/fs.js
Expand Up @@ -36,54 +36,20 @@ function existsSync(path) {
return true;
}

async function _mkdirs(path) {
const parent = dirname(path);

try {
await fsPromises.access(path);
} catch (err) {
if (err.code !== 'ENOENT') throw err;
await _mkdirs(parent);
}

try {
await fsPromises.mkdir(path);
} catch (err) {
if (err.code !== 'EEXIST') throw err;
}
}

function mkdirs(path, callback) {
if (!path) throw new TypeError('path is required!');

return Promise.resolve(_mkdirs(path)).asCallback(callback);
return Promise.resolve(fsPromises.mkdir(path, { recursive: true })).asCallback(callback);
}

function mkdirsSync(path) {
if (!path) throw new TypeError('path is required!');

const parent = dirname(path);

if (!fs.existsSync(parent)) mkdirsSync(parent);
fs.mkdirSync(path);
fs.mkdirSync(path, { recursive: true });
}

function checkParent(path) {
return Promise.resolve(_mkdirs(dirname(path)));
}

function checkParentSync(path) {
if (!path) throw new TypeError('path is required!');

const parent = dirname(path);

if (fs.existsSync(parent)) return;

try {
mkdirsSync(parent);
} catch (err) {
if (err.code !== 'EEXIST') throw err;
}
return Promise.resolve(fsPromises.mkdir(dirname(path), { recursive: true }));
}

function writeFile(path, data, options, callback) {
Expand All @@ -100,7 +66,7 @@ function writeFile(path, data, options, callback) {
function writeFileSync(path, data, options) {
if (!path) throw new TypeError('path is required!');

checkParentSync(path);
fs.mkdirSync(dirname(path), { recursive: true });
fs.writeFileSync(path, data, options);
}

Expand All @@ -118,7 +84,7 @@ function appendFile(path, data, options, callback) {
function appendFileSync(path, data, options) {
if (!path) throw new TypeError('path is required!');

checkParentSync(path);
fs.mkdirSync(dirname(path), { recursive: true });
fs.appendFileSync(path, data, options);
}

Expand Down Expand Up @@ -466,7 +432,7 @@ function ensureWriteStream(path, options, callback) {
function ensureWriteStreamSync(path, options) {
if (!path) throw new TypeError('path is required!');

checkParentSync(path);
fs.mkdirSync(dirname(path), { recursive: true });
return fs.createWriteStream(path, options);
}

Expand Down