Skip to content

Commit

Permalink
fs.mkdir(sync) supports recursive option (#55)
Browse files Browse the repository at this point in the history
* fs.mkdir(Sync) support recursive option
* Inline checkParentSync function
  • Loading branch information
segayuu committed Apr 24, 2020
1 parent 4508c6e commit afd256a
Showing 1 changed file with 6 additions and 40 deletions.
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

0 comments on commit afd256a

Please sign in to comment.