How to capture no file for fs.readFileSync()?
I prefer this way of handling this. You can check if the file exists synchronously:
var file = 'info.json';
var content = '';
// Check that the file exists locally
if(!fs.existsSync(file)) {
console.log("File not found");
}
// The file *does* exist
else {
// Read the file and do anything you want
content = fs.readFileSync(file, 'utf-8');
}
Note: if your program also deletes files, this has a race condition as noted in the comments. If however you only write or overwrite files, without deleting them, then this is totally fine.
Basically, fs.readFileSync
throws an error when a file is not found. This error is from the Error
prototype and thrown using throw
, hence the only way to catch is with a try / catch
block:
var fileContents;
try {
fileContents = fs.readFileSync('foo.bar');
} catch (err) {
// Here you get the error when the file was not found,
// but you also get any other error
}
Unfortunately you can not detect which error has been thrown just by looking at its prototype chain:
if (err instanceof Error)
is the best you can do, and this will be true for most (if not all) errors. Hence I'd suggest you go with the code
property and check its value:
if (err.code === 'ENOENT') {
console.log('File not found!');
} else {
throw err;
}
This way, you deal only with this specific error and re-throw all other errors.
Alternatively, you can also access the error's message
property to verify the detailed error message, which in this case is:
ENOENT, no such file or directory 'foo.bar'
Hope this helps.