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


当前回答

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

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

其他回答

我使用下面的函数来测试文件是否存在。它还捕捉到其他例外。因此,如果存在权限问题,例如chmod ugo rwx文件名或在Windows中右键单击->财产->安全->高级->权限条目:空列表。。函数应返回异常。该文件存在,但我们无权访问它。忽略此类异常是错误的。

function fileExists(path) {

  try  {
    return fs.statSync(path).isFile();
  }
  catch (e) {

    if (e.code == 'ENOENT') { // no such file or directory. File really does not exist
      console.log("File does not exist.");
      return false;
    }

    console.log("Exception fs.statSync (" + path + "): " + e);
    throw e; // something else went wrong, we don't have rights, ...
  }
}

异常输出,nodejs错误文档,以防文件不存在:

{
  [Error: ENOENT: no such file or directory, stat 'X:\\delsdfsdf.txt']
  errno: -4058,
  code: 'ENOENT',
  syscall: 'stat',
  path: 'X:\\delsdfsdf.txt'
}

如果我们没有该文件的权限,但存在,则出现异常:

{
  [Error: EPERM: operation not permitted, stat 'X:\file.txt']
  errno: -4048,
  code: 'EPERM',
  syscall: 'stat',
  path: 'X:\\file.txt'
}
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 extra(npm i fs extra)及其fs.ensureFile或用于目录fs.ensure Dir,因为fs.exists已被取消处理,fs.access不建议您在使用该文件后对其进行编辑“在调用fs.open()、fs.readFile()或fs.writeFile()之前,不要使用fs.access()检查文件的可访问性。这样做会引入竞争条件,因为其他进程可能会在两次调用之间更改文件的状态。相反,用户代码应该直接打开/读取/写入文件,并在文件不可访问时处理引发的错误。"

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
}