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


当前回答

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

其他回答

这里有一个简单的包装解决方案:

var fs = require('fs')
function getFileRealPath(s){
    try {return fs.realpathSync(s);} catch(e){return false;}
}

用法:

适用于目录和文件如果项存在,则返回文件或目录的路径如果项不存在,则返回false

例子:

var realPath,pathToCheck='<your_dir_or_file>'
if( (realPath=getFileRealPath(pathToCheck)) === false){
    console.log('file/dir not found: '+pathToCheck);
} else {
    console.log('file/dir exists: '+realPath);
}

确保使用==运算符测试return是否等于false。在适当的工作条件下,fs.realpathSync()返回false是没有逻辑原因的,所以我认为这应该可以100%工作。

我更希望看到一个不会产生错误和性能影响的解决方案。从API的角度来看,fs.exists()似乎是最优雅的解决方案。

fs.exists()已弃用,请勿使用https://nodejs.org/api/fs.html#fs_fs_exists_path_callback

您可以使用以下方式实现核心nodejs: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;
}

这将返回stats对象,然后在获得stats对象后,您可以尝试

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

为那些“正确”指出它不能直接回答问题的人更新了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()上的文档。

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

文件是否存在?

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

使用fileSystem(fs)测试将触发错误对象,然后需要将其包装在try/catch语句中。节省一些精力,使用0.4.x分支中介绍的功能。

var path = require('path');

var dirs = ['one', 'two', 'three'];

dirs.map(function(dir) {
  path.exists(dir, function(exists) {
    var message = (exists) ? dir + ': is a directory' : dir + ': is not a directory';
    console.log(message);
  });
});