如何捕获fs.readFileSync()的文件? [英] How to capture no file for fs.readFileSync()?
问题描述
在node.js中 readFile()显示了如何捕获错误,但是没有任何评论有关错误处理的 readFileSync()功能。因此,如果我没有文件时尝试使用readFileSync(),我会收到错误错误:ENOENT,没有这样的文件或目录
。
Within node.js readFile() shows how to capture an error, however there is no comment for the readFileSync() function regarding error handling. As such, if I try to use readFileSync() when there is no file, I get the error Error: ENOENT, no such file or directory
.
如何捕获抛出的异常?该doco没有说明抛出什么异常,所以我不知道什么异常我需要抓住。我应该注意到,我不喜欢通用的'catch每一个可能的异常'风格的try / catch语句。在这种情况下,我希望捕获该文件不存在时发生的特定异常,并尝试执行readFileSync。
How do I capture the exception being thrown? The doco doesn't state what exceptions are thrown, so I don't know what exceptions I need to catch. I should note that I don't like generic 'catch every single possible exception' style of try/catch statements. In this case I wish to catch the specific exception that occurs when the file doesn't exist and I attempt to perform the readFileSync.
请注意,我正在执行同步仅在启动连接尝试之前才起作用,所以不需要使用同步功能的注释:-)
Please note that I'm performing sync functions only on start up before serving connection attempts, so comments that I shouldn't be using sync functions are not required :-)
推荐答案
p>基本上, fs.readFileSync
在找不到文件时会引发错误。这个错误来自错误
原型并使用 throw
抛出,因此唯一的方法是使用 try / catch
block:
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'
希望这有帮助。
这篇关于如何捕获fs.readFileSync()的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!