Check synchronously if file/directory exists in Node.js

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

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

15条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 13:06

    The documents on fs.stat() says to use fs.access() if you are not going to manipulate the file. It did not give a justification, might be faster or less memeory use?

    I use node for linear automation, so I thought I share the function I use to test for file existence.

    var fs = require("fs");
    
    function exists(path){
        //Remember file access time will slow your program.
        try{
            fs.accessSync(path);
        } catch (err){
            return false;
        }
        return true;
    }
    

提交回复
热议问题