How do you check if a file exist locally with an electron app

Viewed 5466

I am trying to see if a file exists locally like this:

if (exec(`-f ~/.config/myApp/bookmarks.json`)) {
  console.log('exists')
} else {
  console.log('does not')
}

However, I get exists in the console whether the file exists or not

1 Answers

You should import the fs module into your code. If you're running on the mainprocess, then do a simple const fs = require('fs'); but if you're on the renderer process then run const fs = require('electron').remote.require('fs')

Then with the fs module you can run a simple exists method on the file:

if (fs.existsSync(`~/.config/myApp/bookmarks.json`)) {
  console.log('exists')
} else {
  console.log('does not')
}

Although you really should check for this asynchronously:

fs.access(`~/.config/myApp/bookmarks.json`, (err) => {
  if (err) {
      console.log('does not exist')
    } else {
      console.log('exists')
    }
})
Related