Node.js check if file exists

前端 未结 17 905
生来不讨喜
生来不讨喜 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: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;
    }
    

提交回复
热议问题