diff --git a/lib/appenders/fileSync.js b/lib/appenders/fileSync.js index 4b6109c..b587dbe 100755 --- a/lib/appenders/fileSync.js +++ b/lib/appenders/fileSync.js @@ -11,6 +11,40 @@ function touchFile(file, options) { return; } + // attempt to create the directory + const mkdir = (dir) => { + try { + return fs.mkdirSync(dir, {recursive: true}); + } + // backward-compatible fs.mkdirSync for nodejs pre-10.12.0 (without recursive option) + catch (e) { + // recursive creation of parent first + if (e.code === 'ENOENT') { + mkdir(path.dirname(dir)); + return mkdir(dir); + } + + // throw error for all except EEXIST and EROFS (read-only filesystem) + if (e.code !== 'EEXIST' && e.code !== 'EROFS') { + throw e; + } + + // EEXIST: throw if file and not directory + // EROFS : throw if directory not found + else { + try { + if (fs.statSync(dir).isDirectory()) { + return dir; + } + throw e; + } catch (err) { + throw e; + } + } + } + }; + mkdir(path.dirname(file)); + // touch the file to apply flags (like w to truncate the file) const id = fs.openSync(file, options.flags, options.mode); fs.closeSync(id);