Javascript nodejs fs.exists()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13589070/
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
nodejs fs.exists()
提问by ubiQ
I'm trying to call fs.existsin a node script but I get the error:
我正在尝试调用fs.exists节点脚本,但出现错误:
TypeError: Object # has no method 'exists'
类型错误:对象 # 没有方法“存在”
I've tried replacing fs.exists()with require('fs').existsand even require('path').exists(just in case), but neither of these even list the method exists()with my IDE. fsis declared at the top of my script as fs = require('fs');and I've used it previously to read files.
我试着更换fs.exists()用require('fs').exists,甚至require('path').exists(以防万一),但是没有这些,即使列表的方法exists()与我的IDE。fs在我的脚本顶部声明为fs = require('fs');,我以前用它来读取文件。
How can I call exists()?
我怎样才能打电话exists()?
回答by lostsource
Your require statement may be incorrect, make sure you have the following
您的 require 语句可能不正确,请确保您具有以下内容
var fs = require("fs");
fs.exists("/path/to/file",function(exists){
// handle result
});
Read the documentation here
在这里阅读文档
回答by Warren Parad
You should be using fs.statsor fs.accessinstead. From the node documentation, exists is deprecated (possibly removed.)
您应该使用fs.stats或fs.access代替。从节点文档中,不推荐使用(可能已删除。)
If you are trying to do more than check existence, the documentation says to use fs.open. To example
如果您想做的不仅仅是检查存在,文档说要使用fs.open. 举例
fs.access('myfile', (err) => {
if (!err) {
console.log('myfile exists');
return;
}
console.log('myfile does not exist');
});
回答by Scott Stensland
Do NOT use fs.exists please read its API doc for alternative
不要使用 fs.exists 请阅读其 API 文档以获取替代方案
this is the suggested alternative : go ahead and open file then handle error if any :
这是建议的替代方法:继续打开文件,然后处理错误(如果有):
var fs = require('fs');
var cb_done_open_file = function(interesting_file, fd) {
console.log("Done opening file : " + interesting_file);
// we know the file exists and is readable
// now do something interesting with given file handle
};
// ------------ open file -------------------- //
// var interesting_file = "/tmp/aaa"; // does not exist
var interesting_file = "/some/cool_file";
var open_flags = "r";
fs.open(interesting_file, open_flags, function(error, fd) {
if (error) {
// either file does not exist or simply is not readable
throw new Error("ERROR - failed to open file : " + interesting_file);
}
cb_done_open_file(interesting_file, fd);
});
回答by CertainPerformance
As others have pointed out, fs.existsis deprecated, in part because it uses a single (success: boolean)parameter instead of the muchmore common (error, result)parameters present nearly everywhere else.
正如其他人所指出的那样,fs.exists已被弃用,部分原因是它使用单一(success: boolean)参数代替的多比较常见的(error, result)参数目前几乎其他任何地方。
However, fs.existsSyncis notdeprecated (because it doesn't use a callback, it just returns a value), and if the whole rest of your script depends on checking the existence of a single file, it can make things easier than having to deal with callbacks or surrounding the call with try/catch(in the case of accessSync):
但是,fs.existsSync并没有被弃用(因为它不使用回调,它只返回一个值),如果脚本的其余部分都依赖于检查单个文件的存在,那么它可以使事情变得比不得不处理更容易回调或用try/包围调用catch(在 的情况下accessSync):
const fs = require('fs');
if (fs.existsSync(path)) {
// It exists
} else {
// It doesn't exist
}
Of course, existsSyncis synchronous and blocking. While this can sometimes be handy, if you need to do other operations in parallel (such as checking for the existence of multiple files at once), you should use one one of the other callback-based methods.
当然existsSync是同步和阻塞。虽然这有时很方便,但如果您需要并行执行其他操作(例如一次检查多个文件的存在),您应该使用其他基于回调的方法之一。
Modern versions of Node also support promise-based versions of fsmethods, which one might prefer over callbacks:
现代版本的 Node 还支持基于 Promise 的fs方法版本,人们可能更喜欢回调:
fs.promises.access(path)
.then(() => {
// It exists
})
.catch(() => {
// It doesn't exist
});
回答by ThomasReggi
Here's a solution that uses bluebird to replace the existing exists.
这是一个使用 bluebird 替换现有存在的解决方案。
var Promise = require("bluebird")
var fs = Promise.promisifyAll(require('fs'))
fs.existsAsync = function(path){
return fs.openAsync(path, "r").then(function(stats){
return true
}).catch(function(stats){
return false
})
}
fs.existsAsync("./index.js").then(function(exists){
console.log(exists) // true || false
})

