search

Home  >  Q&A  >  body text

node.js - node如何判断文件夹是否存在呢?

console.log(fs.statSync('./_test/'));
如果_test不存在,会报错。并没有返回值,那么如何判断文件夹是否存在呢?


忘记说了我是node6, fs.exists这个文档已经明确指出 废弃了

高洛峰高洛峰2823 days ago771

reply all(4)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 15:32:36

    fs.exists is deprecated, it is recommended to use fs.stat and fs.access. The following is what I use in my project:

    //检测文件或者文件夹存在 nodeJS
    function fsExistsSync(path) {
        try{
            fs.accessSync(path,fs.F_OK);
        }catch(e){
            return false;
        }
        return true;
    }

    Of course, this is only the synchronous version. If you need an asynchronous version, you can modify it yourself~ If it is useful, please update it below your question so that future generations can view it.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 15:32:36

    https://nodejs.org/dist/lates...
    Here are detailed instructions, take a look

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 15:32:36

    Use where node

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 15:32:36

    I remember that there is fs.exists and fs.existsSync, both of which can determine whether it exists. The latter one is synchronous

    reply
    0
  • Cancelreply