fs.existsSync()

Check if file exists

Synchronously checks if a file exists in the given path.

Alternatives to fs.existsSync()

While fs.existsSync() is not deprecated, it's often recommended to use other methods for checking file existence.

  • fs.access(): This method checks the accessibility of a file. It's a more reliable way to check if a file exists and can be accessed.
  • fs.stat(): This method returns information about a file. You can use it to check if a file exists by checking if the err parameter is null.

Example Usage

const fs = require('fs');

// Using fs.access()
fs.access('path/to/file', (err) => {
    if (err) {
        console.log('File does not exist or is inaccessible');
    } else {
        console.log('File exists and is accessible');
    }
});

// Using fs.stat()
fs.stat('path/to/file', (err, stats) => {
    if (err) {
        console.log('File does not exist');
    } else {
        console.log('File exists');
    }
});

Important Notes

  • When using fs.existsSync() with symlinks, it may return false even if the symlink exists. This is a known issue and has been reported in the Node.js repository.
  • Some developers recommend avoiding fs.existsSync() due to its historical nature and potential issues. However, it's still a part of the Node.js API and can be used if needed.
Show web results