Node.js check if file exists

前端 未结 17 873
生来不讨喜
生来不讨喜 2020-12-07 10:02

How do i check the existence of a file?

In the documentation for the module fs there\'s a description of the method fs.exists(path, cal

相关标签:
17条回答
  • 2020-12-07 10:27

    Why not just try opening the file ? fs.open('YourFile', 'a', function (err, fd) { ... }) anyway after a minute search try this :

    var path = require('path'); 
    
    path.exists('foo.txt', function(exists) { 
      if (exists) { 
        // do something 
      } 
    }); 
    
    // or 
    
    if (path.existsSync('foo.txt')) { 
      // do something 
    } 
    

    For Node.js v0.12.x and higher

    Both path.exists and fs.exists have been deprecated

    *Edit:

    Changed: else if(err.code == 'ENOENT')

    to: else if(err.code === 'ENOENT')

    Linter complains about the double equals not being the triple equals.

    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);
        }
    });
    
    0 讨论(0)
  • 2020-12-07 10:29

    There are a lot of inaccurate comments about fs.existsSync() being deprecated; it is not.

    https://nodejs.org/api/fs.html#fs_fs_existssync_path

    Note that fs.exists() is deprecated, but fs.existsSync() is not.

    0 讨论(0)
  • 2020-12-07 10:30

    Old Version before V6: here's the documentation

      const fs = require('fs');    
      fs.exists('/etc/passwd', (exists) => {
         console.log(exists ? 'it\'s there' : 'no passwd!');
      });
    // or Sync
    
      if (fs.existsSync('/etc/passwd')) {
        console.log('it\'s there');
      }
    

    UPDATE

    New versions from V6: documentation for fs.stat

    fs.stat('/etc/passwd', function(err, stat) {
        if(err == null) {
            //Exist
        } else if(err.code == 'ENOENT') {
            // NO exist
        } 
    });
    
    0 讨论(0)
  • 2020-12-07 10:31

    Edit: Since node v10.0.0we could use fs.promises.access(...)

    Example async code that checks if file exists:

    async function checkFileExists(file) {
      return fs.promises.access(file, fs.constants.F_OK)
               .then(() => true)
               .catch(() => false)
    }
    

    An alternative for stat might be using the new fs.access(...):

    minified short promise function for checking:

    s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))
    

    Sample usage:

    let checkFileExists = s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))
    checkFileExists("Some File Location")
      .then(bool => console.log(´file exists: ${bool}´))
    

    expanded Promise way:

    // returns a promise which resolves true if file exists:
    function checkFileExists(filepath){
      return new Promise((resolve, reject) => {
        fs.access(filepath, fs.constants.F_OK, error => {
          resolve(!error);
        });
      });
    }
    

    or if you wanna do it synchronously:

    function checkFileExistsSync(filepath){
      let flag = true;
      try{
        fs.accessSync(filepath, fs.constants.F_OK);
      }catch(e){
        flag = false;
      }
      return flag;
    }
    
    0 讨论(0)
  • async/await version using util.promisify as of Node 8:

    const fs = require('fs');
    const { promisify } = require('util');
    const stat = promisify(fs.stat);
    
    describe('async stat', () => {
      it('should not throw if file does exist', async () => {
        try {
          const stats = await stat(path.join('path', 'to', 'existingfile.txt'));
          assert.notEqual(stats, null);
        } catch (err) {
          // shouldn't happen
        }
      });
    });
    
    describe('async stat', () => {
      it('should throw if file does not exist', async () => {
        try {
          const stats = await stat(path.join('path', 'to', 'not', 'existingfile.txt'));
        } catch (err) {
          assert.notEqual(err, null);
        }
      });
    });
    
    0 讨论(0)
  • 2020-12-07 10:35

    You can use fs.stat to check if target is a file or directory and you can use fs.access to check if you can write/read/execute the file. (remember to use path.resolve to get full path for the target)

    Documentation:

    • path.resolve
    • fs.stat
    • fs.access

    Full example (TypeScript)

    import * as fs from 'fs';
    import * as path from 'path';
    
    const targetPath = path.resolve(process.argv[2]);
    
    function statExists(checkPath): Promise<fs.Stats> {
      return new Promise((resolve) => {
        fs.stat(checkPath, (err, result) => {
          if (err) {
            return resolve(undefined);
          }
    
          return resolve(result);
        });
      });
    }
    
    function checkAccess(checkPath: string, mode: number = fs.constants.F_OK): Promise<boolean> {
      return new Promise((resolve) => {
        fs.access(checkPath, mode, (err) => {
          resolve(!err);
        });
      });
    }
    
    (async function () {
      const result = await statExists(targetPath);
      const accessResult = await checkAccess(targetPath, fs.constants.F_OK);
      const readResult = await checkAccess(targetPath, fs.constants.R_OK);
      const writeResult = await checkAccess(targetPath, fs.constants.W_OK);
      const executeResult = await checkAccess(targetPath, fs.constants.X_OK);
      const allAccessResult = await checkAccess(targetPath, fs.constants.F_OK | fs.constants.R_OK | fs.constants.W_OK | fs.constants.X_OK);
    
      if (result) {
        console.group('stat');
        console.log('isFile: ', result.isFile());
        console.log('isDir: ', result.isDirectory());
        console.groupEnd();
      }
      else {
        console.log('file/dir does not exist');
      }
    
      console.group('access');
      console.log('access:', accessResult);
      console.log('read access:', readResult);
      console.log('write access:', writeResult);
      console.log('execute access:', executeResult);
      console.log('all (combined) access:', allAccessResult);
      console.groupEnd();
    
      process.exit(0);
    }());
    
    0 讨论(0)
提交回复
热议问题