Check synchronously if file/directory exists in Node.js

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

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

15条回答
  •  借酒劲吻你
    2020-11-22 13:11

    fs.exists() is deprecated dont use it https://nodejs.org/api/fs.html#fs_fs_exists_path_callback

    You could implement the core nodejs way used at this: https://github.com/nodejs/node-v0.x-archive/blob/master/lib/module.js#L86

    function statPath(path) {
      try {
        return fs.statSync(path);
      } catch (ex) {}
      return false;
    }
    

    this will return the stats object then once you've got the stats object you could try

    var exist = statPath('/path/to/your/file.js');
    if(exist && exist.isFile()) {
      // do something
    }
    

提交回复
热议问题