nodejs fs.exists()
我试图在一个节点脚本中调用fs.exists
,但是我得到错误:
TypeError:Object#没有方法'exists'
我尝试用require('fs').exists
replacefs.exists()
,甚至require('path').exists
(以防万一),但是这两个都没有列出方法exists()
与我的IDE。 fs
在我的脚本的顶部声明为fs = require('fs');
我以前用它来读取文件。
我怎样才能调用exists()
?
您的要求声明可能不正确,请确保您有以下要求
var fs = require("fs"); fs.exists("/path/to/file",function(exists){ // handle result });
阅读这里的文档
不要使用fs.exists 请阅读它的API文档替代
这是build议的替代方法:继续并打开文件,然后处理错误,如果有的话:
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); });
您应该使用fs.stats
或fs.access
来代替。 从节点文档中 ,存在已被弃用(可能被删除)。
如果你正在努力做更多的检查存在,文件说使用fs.open
。 举个例子
fs.access('myfile', (err) => { if (!err) { console.log('myfile exists'); return; } console.log('myfile does not exist'); });
这是一个使用蓝鸟取代现有的存在的解决scheme。
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 })