John John - 1 year ago 241
Node.js Question

How to check if a file or directory exists without using fs.exists?

The reason I ask, is because Node.js on ubuntu doesn't seem to have the fs.exists() function. Although I can call this when I run Node.js on my Mac, when I deploy to the server, it fails with an error saying the function does not exist.

Now, I am aware that some people consider it an "anti-pattern" to check if a file exists and then try and edit / open it etc, but in my case, I never delete these files, but I still need to check if they exist before writing to them.

So how can I check if the directory (or file) exists ?


This is the code I run in a file called 'temp.'s' :

var fs=require('fs');

On my Mac, it works fine. On ubuntu I get the error:

throw e; // process.nextTick error, or 'error' event on first tick
^ TypeError: Object #<Object> has no method 'exists'
at Object.<anonymous> (/home/banana/temp.js:2:4)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:32)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
at EventEmitter._tickCallback (node.js:192:41)

On my Mac - version : v0.13.0-pre
On Ubuntu - version : v0.6.12

Answer Source

It's probably due to the fact that in NodeJs 0.6 the exists() method was located in the path module:

^^ That comment answers why it isn't there. I'll answer what you can do about it (besides not using ancient versions).

From the fs.exists() documentation:

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.exists() and Just open the file and handle the error when it's not there.

You could do something like this:'mypath','r',function(err,fd){
    if (err && err.code=='ENOENT') { /* file doesn't exist */ }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download