Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs fs.exists()

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()?

like image 811
ubiQ Avatar asked Nov 27 '12 16:11

ubiQ


People also ask

How do you check if a file exists with fs?

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.

Why is fs deprecated?

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.

What does fs do in node?

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.

What is fs in Require (' fs ')?

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.

What is the use of fs unlink ()?

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.


2 Answers

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

like image 180
lostsource Avatar answered Sep 21 '22 16:09

lostsource


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'); }); 
like image 39
Warren Parad Avatar answered Sep 21 '22 16:09

Warren Parad