Check synchronously if file/directory exists in Node.js

前端 未结 15 2115
梦如初夏
梦如初夏 2020-11-22 12:26

How can I synchronously check, using node.js, if a file or directory exists?

相关标签:
15条回答
  • 2020-11-22 13:13

    Chances are, if you want to know if a file exists, you plan to require it if it does.

    function getFile(path){
        try{
            return require(path);
        }catch(e){
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 13:17

    Some answers here says that fs.exists and fs.existsSync are both deprecated. According to the docs this is no more true. Only fs.exists is deprected now:

    Note that fs.exists() is deprecated, but fs.existsSync() is not. (The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.)

    So you can safely use fs.existsSync() to synchronously check if a file exists.

    0 讨论(0)
  • 2020-11-22 13:23

    updated asnwer for those people 'correctly' pointing out it doesnt directly answer the question, more bring an alternative option.

    Sync solution:

    fs.existsSync('filePath') also see docs here.

    Returns true if the path exists, false otherwise.

    Async Promise solution

    In an async context you could just write the async version in sync method with using the await keyword. You can simply turn the async callback method into an promise like this:

    function fileExists(path){
      return new Promise((resolve, fail) => fs.access(path, fs.constants.F_OK, 
        (err, result) => err ? fail(err) : resolve(result))
      //F_OK checks if file is visible, is default does no need to be specified.
    
    }
    
    async function doSomething() {
      var exists = await fileExists('filePath');
      if(exists){ 
        console.log('file exists');
      }
    }
    

    the docs on access().

    0 讨论(0)
提交回复
热议问题