如何使用node.js同步检查文件或目录是否存在?


当前回答

很可能,如果你想知道文件是否存在,你计划在它存在的时候需要它。

function getFile(path){
    try{
        return require(path);
    }catch(e){
        return false;
    }
}

其他回答

❄️ 可以使用图形fs

directory.exists // boolean
const fs = require('fs');

检查以下功能,

if(fs.existsSync(<path_that_need_to_be_checked>)){
  // enter the code to excecute after the folder is there.
}
else{
  // Below code to create the folder, if its not there
  fs.mkdir('<folder_name>', cb function);
}

这里的一些答案表示fs.exists和fs.existsSync都已弃用。根据文件,这不再是事实。现在只弃用fs.exists:

请注意,fs.exists()已弃用,但fs.existsSync()未弃用。(fs.exists()的回调参数接受以下参数与其他Node.js回调不一致。fs.existsSync()不使用回调。)

因此,您可以安全地使用fs.existsSync()同步检查文件是否存在。

为那些“正确”指出它不能直接回答问题的人更新了asnwer,更多的是带来了一个替代选项。

同步解决方案:

fs.existsSync('filePath')也可以在此处查看文档。

如果路径存在,则返回true,否则返回false。

Async Promise解决方案

在异步上下文中,您可以使用await关键字编写异步版本同步方法。您可以简单地将异步回调方法转换为如下承诺:

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');
  }
}

access()上的文档。

另一个更新

我自己需要这个问题的答案,我查阅了节点文档,似乎您不应该使用fs.exists,而是使用fs.open并使用输出的错误来检测文件是否不存在:

从文档中:

fs.exists()是一个时代错误,只因历史原因而存在。在您自己的代码中使用它几乎没有任何理由。特别是,在打开文件之前检查文件是否存在让你容易受到种族状况影响的反模式:另一种进程可能会在调用fs.exists()和fs.open()。只需打开文件并在不存在时处理错误那里

http://nodejs.org/api/fs.html#fs_fs_exists_path_callback