Node.js check if file exists

Consider opening the file directly, to avoid race conditions:

const fs = require('fs');

fs.open('foo.txt', 'r', function (err, fd) {
  // ...
});

Using fs.existsSync:

if (fs.existsSync('foo.txt')) {
  // ...
}

Using fs.stat:

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);
  }
});

Deprecated:

fs.exists is deprecated.

Using path.exists:

const path = require('path');

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

Using path.existsSync:

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

Leave a Comment