I'm trying to call fs.exists
in a node script but I get the error:
TypeError: Object # has no method 'exists'
I've tried replacing fs.exists()
with require('fs').exists
and even require('path').exists
(just in case), but neither of these even list the method exists()
with my IDE. fs
is declared at the top of my script as fs = require('fs');
and I've used it previously to read files.
How can I call exists()
?
Your require statement may be incorrect, make sure you have the following
var fs = require("fs");
fs.exists("/path/to/file",function(exists){
// handle result
});
Read the documentation here
Do NOT use fs.exists please read its API doc for alternative
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);
});
Here's a solution that uses bluebird to replace the existing exists.
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
})