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()
?
Checking file existence with existsSync() The fs. existsSync() method allows you to check for the existence of a file by tracing if a specified path can be accessed from the current directory where the script is executed. It returns true when the path exists and false when it's not.
exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code. In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.
The Node. js fs module provides two different functions for writing files: writeFile and writeFileSync . Both functions take a file path and data as arguments, and write the data to the specified file.
The Node.js file system module allows you to work with the file system on your computer. To include the File System module, use the require() method: var fs = require('fs'); Common use for the File System module: Read files.
The fs. unlink() method is used to remove a file or symbolic link from the filesystem. This function does not work on directories, therefore it is recommended to use fs. rmdir() to remove a directory.
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
http://nodejs.org/api/fs.html#fs_fs_exists_path_callback
You should be using fs.stats
or fs.access
instead. From the node documentation, exists is deprecated (possibly removed.)
If you are trying to do more than check existence, the documentation says to use fs.open
. To example
fs.access('myfile', (err) => { if (!err) { console.log('myfile exists'); return; } console.log('myfile does not exist'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With