我正在创建一个函数,它使用 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/