node.jsfs

Node.js check if file exists


How do I check for the existence of a file?


Solution

  • Consider opening or reading the file directly, to avoid race conditions:

    const fs = require('fs');
    
    fs.open('foo.txt', 'r', (err, fd) => {
      // ...
    });
    
    fs.readFile('foo.txt', (err, data) => {
      if (!err && data) {
        // ...
      }
    })
    
    

    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')) { 
      // ...
    }