javascript - fs.statSync 包含在函数中时会抛出错误?

标签 javascript node.js exists fs

我正在创建一个函数,它使用 fs.statSync 返回一个 bool 值来判断文件是否存在。它看起来像这样:

function doesExist (cb) {
  let exists
  try {
    fs.statSync('./cmds/' + firstInitial + '.json')
    exists = true
  } catch (err) {
    exists = err && err.code === 'ENOENT' ? false : true
  }
  cb(exists)
}

示例用例:

let fileExists
doesExist('somefile.json', function (exists) {
  fileExists = exists
})

但是,运行代码会抛出一个TypeError: string is not a function。我不知道为什么。

最佳答案

我想你想删除那个回调,并将文件名添加到你的参数中:

function doesExist(firstInitial) {
  try {
    fs.statSync('./cmds/' + firstInitial + '.json')
    return true
  } catch(err) {
    return !(err && err.code === 'ENOENT');
  }
}

let fileExists = doesExist('somefile');

顺便说一句,还有fs.exists .

关于javascript - fs.statSync 包含在函数中时会抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29316550/

相关文章:

javascript - WMS 图层未在所有缩放级别上正确渲染

php - 将未设置的变量传递给函数

javascript - 对象中的NodeJs FindbyId

node.js - 如何在单个液滴上将不同的 MERN 应用程序部署到 digital ocean ?

node.js - Karma/Grunt 未加载 Chai 变量

sql - 在特定日期之前查询没有值

sql - 检查表A中的条目是否存在于表B中

javascript - jQuery动画到容器的高度

javascript - 在 reactjs 中更改 scrollTop

javascript - 在javascript中访问对象内的数组?