admin管理员组

文章数量:1302902

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

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

Share asked Dec 18, 2018 at 21:14 ss_matchesss_matches 5172 gold badges6 silver badges21 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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')
    }
})

本文标签: javascriptHow do you check if a file exist locally with an electron appStack Overflow