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 to if 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
 |  Show 1 more ment

1 Answer 1

Reset to default 4

Finally, 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