node.js 如何为 fs.readFileSync() 捕获无文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14391690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to capture no file for fs.readFileSync()?
提问by Metalskin
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.
在 node.js readFile() 中展示了如何捕获错误,但是readFileSync()函数没有关于错误处理的注释。因此,如果我在没有文件的情况下尝试使用 readFileSync(),则会出现错误Error: ENOENT, no such file or directory。
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.
如何捕获抛出的异常?doco 没有说明抛出什么异常,所以我不知道我需要捕获什么异常。我应该注意,我不喜欢 try/catch 语句的通用“捕获每个可能的异常”样式。在这种情况下,我希望捕获文件不存在时发生的特定异常,并且我尝试执行 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 :-)
请注意,我仅在启动连接尝试之前执行同步功能,因此不需要我不应该使用同步功能的评论:-)
回答by Golo Roden
Basically, fs.readFileSyncthrows an error when a file is not found. This error is from the Errorprototype and thrown using throw, hence the only way to catch is with a try / catchblock:
基本上,fs.readFileSync当找不到文件时抛出错误。此错误来自Error原型并使用 抛出throw,因此捕获的唯一方法是使用try / catch块:
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 codeproperty and check its value:
是你能做的最好的,这对于大多数(如果不是全部)错误都是正确的。因此,我建议您使用该code物业并检查其价值:
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 messageproperty to verify the detailed error message, which in this case is:
或者,您还可以访问错误的message属性来验证详细的错误消息,在本例中为:
ENOENT, no such file or directory 'foo.bar'
Hope this helps.
希望这可以帮助。
回答by Francisco Presencia
While the accepted solution is okay, I found a much better way of handling this. You can just 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(this.local, 'utf-8');
}
回答by loganfsmyth
You have to catch the error and then check what type of error it is.
您必须捕获错误,然后检查它是什么类型的错误。
try {
var data = fs.readFileSync(...)
} catch (err) {
// If the type is not what you want, then just throw the error again.
if (err.code !== 'ENOENT') throw err;
// Handle a file-not-found error
}
回答by sdgfsdh
I use an immediately invoked lambda for these scenarios:
对于这些场景,我使用立即调用的 lambda:
const config = (() => {
try {
return JSON.parse(fs.readFileSync('config.json'));
} catch (error) {
return {};
}
})();
asyncversion:
async版本:
const config = await (async () => {
try {
return JSON.parse(await fs.readFileAsync('config.json'));
} catch (error) {
return {};
}
})();
回答by jdnichollsc
Try using Asyncinstead to avoid blocking the only thread you have with NodeJS. Check this example:
尝试使用Async来避免阻塞 NodeJS 的唯一线程。检查这个例子:
const util = require('util');
const fs = require('fs');
const path = require('path');
const readFileAsync = util.promisify(fs.readFile);
const readContentFile = async (filePath) => {
// Eureka, you are using good code practices here!
const content = await readFileAsync(path.join(__dirname, filePath), {
encoding: 'utf8'
})
return content;
}
Later can use this async function with try/catch from any other function:
稍后可以将此异步函数与来自任何其他函数的 try/catch 一起使用:
const anyOtherFun = async () => {
try {
const fileContent = await readContentFile('my-file.txt');
} catch (err) {
// Here you get the error when the file was not found,
// but you also get any other error
}
}
Happy Coding!
快乐编码!

