Check synchronously if file/directory exists in Node.js

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

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

15条回答
  •  执笔经年
    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().

提交回复
热议问题