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


当前回答

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

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

其他回答

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

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

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

function getFile(path){
    try{
        return require(path);
    }catch(e){
        return false;
    }
}
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

directory.exists // boolean