node.js 如果文件不存在,fs.statSync 会抛出错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33400294/
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
fs.statSync throws error if file does not exist
提问by Mike
I am attempting to determine if a file exists. If it does not exist, I would like my code to continue so it will be created. When I use the following code, if the file exists, it prints that 'it exists'. If it does not exist, it crashes my app. Here is my code:
我正在尝试确定文件是否存在。如果它不存在,我希望我的代码继续,以便创建它。当我使用以下代码时,如果文件存在,它会打印“它存在”。如果它不存在,它会使我的应用程序崩溃。这是我的代码:
var checkDuplicateFile = function(){
var number = room.number.toString();
var stats = fs.statSync(number);
if(stat){
console.log('it exists');
}else{
console.log('it does not exist');
}
};
回答by peteb
Your application is crashing because you're not wrapping your fs.statSyncin a try/catchblock. Sync functions in node don't return the error like they would in their asyncversions. Instead, they throw their errors which need to be caught.
您的应用程序崩溃了,因为您没有将您的应用程序包装fs.statSync在一个try/catch块中。node 中的同步函数不会像在它们的async版本中那样返回错误。相反,他们抛出需要被捕获的错误。
try {
var stats = fs.statSync(number);
console.log('it exists');
}
catch(err) {
console.log('it does not exist');
}
If your app doesn't require this operation to be synchronous (block further execution until this operation is finished) then I would use the async version.
如果您的应用不需要同步此操作(在此操作完成之前阻止进一步执行),那么我将使用异步版本。
fs.stat(number, function(err, data) {
if (err)
console.log('it does not exist');
else
console.log('it exists');
});

