G
G
gleendo2017-07-29 08:05:10
Node.js
gleendo, 2017-07-29 08:05:10

How to check the existence of a file?

The code examples use the exists method, but it is Deprecated: Use fs.stat() or fs.access() instead.
How to use these methods to check if a file exists?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dummyman, 2017-07-29
@evgeniy8705

Prior to Node v0.10 fs.exists() and path.exists() were working

var path = require('path'); 

path.exists('foo.txt', function(exists) { 
  if (exists) { 
    // do something 
  } 
}); 


if (path.existsSync('foo.txt')) { 
  // do something 
}

After, Node >= v0.12
fs.stat('foo.txt', function(err, stat) {
    if(err == null) {
        console.log('File exists');
    } else if(err.code == 'ENOENT') {
        // file does not exist
        fs.writeFile('log.txt', 'Some log\n');
    } else {
        console.log('Some other error: ', err.code);
    }
});

stackoverflow

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question