fs.statSync包含在函数中时抛出错误

fs.statSync throws an error when contained in a function?

本文关键字:出错 错误 函数 statSync 包含 fs      更新时间:2023-09-26

我正在制作一个函数,该函数使用fs.statSync返回文件存在与否的布尔值。它看起来像这样:

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

相关文章: