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


当前回答

这已经得到了回答,但如果您喜欢安装模块,可以使用dtfe,它代表

文件是否存在?

const dtfe = require('dtfe');
 
dtfe('package.json');
//=> true

其他回答

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

为那些“正确”指出它不能直接回答问题的人更新了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 extra(npm i fs extra)及其fs.ensureFile或用于目录fs.ensure Dir,因为fs.exists已被取消处理,fs.access不建议您在使用该文件后对其进行编辑“在调用fs.open()、fs.readFile()或fs.writeFile()之前,不要使用fs.access()检查文件的可访问性。这样做会引入竞争条件,因为其他进程可能会在两次调用之间更改文件的状态。相反,用户代码应该直接打开/读取/写入文件,并在文件不可访问时处理引发的错误。"

查看源代码,有一个同步版本的path.exists-path.existsSync。看起来文档中没有找到它。

更新:

path.exists和path.existsSync现在已弃用。请使用fs.exists和fs.existsSync。

2016年更新:

fs.exists和fs.existsSync也已被弃用。请改用fs.stat()或fs.access()。

2019年更新:

使用fs.existsSync。它没有被弃用。https://nodejs.org/api/fs.html#fs_fs_existssync_path

这已经得到了回答,但如果您喜欢安装模块,可以使用dtfe,它代表

文件是否存在?

const dtfe = require('dtfe');
 
dtfe('package.json');
//=> true