如何为 fs.readFileSync() 不捕获文件? [英] How to capture no file for fs.readFileSync()?

查看:24
本文介绍了如何为 fs.readFileSync() 不捕获文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 node.js 中 readFile() 显示了如何捕获错误,但是没有对readFileSync() 函数关于错误处理.因此,如果我在没有文件时尝试使用 readFileSync(),则会收到错误 Error: ENOENT, no such file or directory.

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 没有说明抛出什么异常,所以我不知道我需要捕获什么异常.我应该注意,我不喜欢 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 :-)

推荐答案

基本上,fs.readFileSync 在找不到文件时会抛出错误.此错误来自 Error 原型并使用 throw 抛出,因此捕获的唯一方法是使用 try/catch 块:

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)

是你能做的最好的,这对于大多数(如果不是全部)错误都是正确的.因此,我建议您使用 code 属性并检查其值:

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.

或者,您也可以访问错误的 message 属性来验证详细的错误消息,在本例中为:

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆