Fixed fileSync appender to create directory recursively

This commit is contained in:
Lam Wei Li 2022-03-01 01:39:38 +08:00
parent 6b927c7c31
commit 287c3eb836
No known key found for this signature in database
GPG Key ID: 90F6ABECF080D7BF

View File

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