You can use fs.access(path[, mode], callback)
, the optional mode
argument can be used to check the accessibility of the file, for example fs.constants.F_OK
check if the file exists and fs.constants.R_OK
indicates that the file is readable. (The full list of File Access Constants)
if (extName === '.json') {
const fullFileNamed = '../../theme-default/resource/i18n';
// console.log (fullFileNamed, "fullFileNamed")
// Check if the file exists in the current directory, and if it is readable.
fs.access(fullFileNamed, fs.constants.F_OK | fs.constants.R_OK, (err) => {
if (err) {
console.error(`${fullFileNamed} ${err.code === 'ENOENT' ? 'does not exist' : 'is not readable'}`);
} else {
console.log(`${fullFileNamed} exists, and it is readable`);
const fileContent = fs.readFileSync(fullFileNamed, 'utf8');
console.log ('fileContent', fileContent);
}
});
}
For synchronous tests use fs.accessSync(path[, mode])
:
try {
fs.accessSync(fullFileNamed, fs.constants.F_OK | fs.constants.R_OK);
console.log(`${fullFileNamed} exists, and it is readable`);
const fileContent = fs.readFileSync(fullFileNamed, 'utf8');
console.log ('fileContent', fileContent);
} catch (err) {
console.error(`${fullFileNamed} ${err.code === 'ENOENT' ? 'does not exist' : 'is not readable'}`);
}