Check synchronously if file/directory exists in Node.js

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

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

15条回答
  •  死守一世寂寞
    2020-11-22 13:09

    Here is a simple wrapper solution for this:

    var fs = require('fs')
    function getFileRealPath(s){
        try {return fs.realpathSync(s);} catch(e){return false;}
    }
    

    Usage:

    • Works for both directories and files
    • If item exists, it returns the path to the file or directory
    • If item does not exist, it returns false

    Example:

    var realPath,pathToCheck=''
    if( (realPath=getFileRealPath(pathToCheck)) === false){
        console.log('file/dir not found: '+pathToCheck);
    } else {
        console.log('file/dir exists: '+realPath);
    }
    

    Make sure you use === operator to test if return equals false. There is no logical reason that fs.realpathSync() would return false under proper working conditions so I think this should work 100%.

    I would prefer to see a solution that does not does not generate an Error and resulting performance hit. From an API perspective, fs.exists() seems like the most elegant solution.

提交回复
热议问题