Javascript nodejs fs.exists()

Javascript nodejs fs.exists(),javascript,node.js,Javascript,Node.js,我正在尝试调用节点脚本中的fs.exists,但出现错误: TypeError:对象#没有方法“exists” 我尝试用require('fs')替换fs.exists()。exists甚至require('path')。exists(以防万一),但这两个方法都没有在我的IDE中列出方法exists()fs在我的脚本顶部声明为fs=require('fs')我以前用过它来读取文件 如何调用exists()?您的require语句可能不正确,请确保您具有以下内容 var fs = require(

我正在尝试调用节点脚本中的
fs.exists
,但出现错误:

TypeError:对象#没有方法“exists”

我尝试用
require('fs')替换
fs.exists()
。exists
甚至
require('path')。exists
(以防万一),但这两个方法都没有在我的IDE中列出方法
exists()
fs
在我的脚本顶部声明为
fs=require('fs')我以前用过它来读取文件


如何调用
exists()

您的require语句可能不正确,请确保您具有以下内容

var fs = require("fs");

fs.exists("/path/to/file",function(exists){
  // handle result
});
请阅读此处的文档

不要使用fs.exists

这是建议的备选方案:继续并打开文件,然后处理错误(如果有):

var fs = require('fs');

var cb_done_open_file = function(interesting_file, fd) {

    console.log("Done opening file : " + interesting_file);

    // we know the file exists and is readable
    // now do something interesting with given file handle
};

// ------------ open file -------------------- //

// var interesting_file = "/tmp/aaa"; // does not exist
var interesting_file = "/some/cool_file";

var open_flags = "r";

fs.open(interesting_file, open_flags, function(error, fd) {

    if (error) {

        // either file does not exist or simply is not readable
        throw new Error("ERROR - failed to open file : " + interesting_file);
    }

    cb_done_open_file(interesting_file, fd);
});

您应该使用
fs.stats
fs.access
。从中,不推荐使用exists(可能已删除)

如果您试图做的不仅仅是检查是否存在,文档中说要使用
fs.open
。以身作则

fs.access('myfile', (err) => {
  if (!err) {
    console.log('myfile exists');
    return;
  }
  console.log('myfile does not exist');
});

正如其他人所指出的,
fs.exists
被弃用,部分原因是它使用了一个
(success:boolean)
参数,而不是其他几乎无处不在的更常见的
(错误、结果)
参数

但是,
fs.existsSync
并没有被弃用(因为它不使用回调,只返回一个值),如果脚本的其余部分都依赖于检查单个文件的存在,那么它可以使处理回调或使用
try
/
catch
(如果是
accessSync
):

当然,
existsSync
是同步和阻塞的。虽然这有时很方便,但如果需要并行执行其他操作(例如一次检查是否存在多个文件),则应使用其他基于回调的方法之一

Node的现代版本还支持基于承诺的
fs
方法版本,人们可能更喜欢使用这些方法而不是回调:

fs.promises.access(path)
  .then(() => {
    // It exists
  })
  .catch(() => {
    // It doesn't exist
  });

如果执行
console.log(Object.keys(fs))会得到什么
?我怀疑IDE是否会正确列出
存在
,所以不要担心。您运行的是哪个版本的节点?
存在
已从移动到
fs
。嘿,伙计们,为帮助干杯,由于某种原因,我的节点已恢复为旧版本,因此我启动并运行了nvm,并安装了最新的版本,all现在可以工作了。从文档中:
fs.exists()
是一种过时现象,仅因历史原因而存在。在您自己的代码中几乎不应该有理由使用它。特别是,在打开文件之前检查文件是否存在是一种反模式,这会使您容易受到竞争条件的影响:另一个进程可能会在调用
fs.exists()之间删除该文件
fs.open()
。只需打开文件,并在文件不存在时处理错误。您可以发布相关的代码部分吗?您可能缺少一个requires或使用不同的版本。我曾经发现一个类似于var myLib='./myLib.js'的错误;因此查看相关代码可能会有所帮助。另外,请注意,您应该将try()catch()阻止阅读该文件的代码。初学者可能会想知道他们应该如何解决这个问题。fs.open是过度杀伤力,fs.access看起来很有希望。这是不推荐的。使用或代替。(注意:注释的原因是这是在Google搜索fs.exists时首先出现的)请小心,因为当文件存在但您没有写入权限时,
fs.access
也会返回错误。请查看更多详细信息。
fs.promises.access(path)
  .then(() => {
    // It exists
  })
  .catch(() => {
    // It doesn't exist
  });