admin管理员组文章数量:1418059
I'm trying to check if a file is exist. So, I apply fs.existsSync() function. But, the problem is this function always return false (not exit).
Written below is my code.
Thank you in advance!
[ My Environment ]
- Ubuntu
- Node.js version 16.14.0
const fs = require('fs')
const getProvinceByCountry = country => {
const filePath = `../../config/province/${country}.json`
const fileExist = fs.existsSync(filePath)
if (!fileExist) {
console.log('File does not exist')
} else {
console.log('File exists')
}
}
// Result : File does not exists.
// existsSync() always returns false even if the path and the file name are correct.
I'm trying to check if a file is exist. So, I apply fs.existsSync() function. But, the problem is this function always return false (not exit).
Written below is my code.
Thank you in advance!
[ My Environment ]
- Ubuntu
- Node.js version 16.14.0
const fs = require('fs')
const getProvinceByCountry = country => {
const filePath = `../../config/province/${country}.json`
const fileExist = fs.existsSync(filePath)
if (!fileExist) {
console.log('File does not exist')
} else {
console.log('File exists')
}
}
// Result : File does not exists.
// existsSync() always returns false even if the path and the file name are correct.
Share
Improve this question
edited Mar 24, 2022 at 15:25
Maker
asked Mar 24, 2022 at 14:37
MakerMaker
1711 silver badge12 bronze badges
6
-
1
Did you try to
console.log()
the file path to make sure it is the right one, since you are relying on a relative path? – Ben Commented Mar 24, 2022 at 14:41 -
Isn't it working correctly? If the file exists it will always go to
else
block because your if condition is!fileExist
. If file doesn't exist it will go toif
block. I don't understand the issue here? Even your console log says - File exists – Shivam Commented Mar 24, 2022 at 15:14 - @ShivamSood oh... my mistake. The result was 'File does not exist' not 'File exist' – Maker Commented Mar 24, 2022 at 15:27
- @Ben the file path is correct. – Maker Commented Mar 24, 2022 at 15:28
-
There doesn't seem to be too many variables in this issue, one of it has to be incorrect. Either Path is incorrect.
Country
parameter doesn't have correct value. Try proving absolute path and console.log the country parameter to check if you are getting correct value. – Shivam Commented Mar 24, 2022 at 15:34
1 Answer
Reset to default 4Finally, I've solve the problem. What I did is use path.join.
const filePath = path.join(__dirname, `../../config/province/${country}.json`)
本文标签: javascriptWhy does fsexistsSync always return falseStack Overflow
版权声明:本文标题:javascript - Why does fs.existsSync always return false? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745248932a2649702.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论