简体   繁体   English

如何使用电子应用程序检查文件是否本地存在

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

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 但是,无论文件是否存在 ,我都会在控制台中存在

You should import the fs module into your code. 您应该将fs模块导入代码中。 If you're running on the main process, then do a simple const fs = require('fs'); 如果您在main进程上运行,则执行一个简单的const fs = require('fs'); but if you're on the renderer process then run const fs = require('electron').remote.require('fs') 但是如果您在渲染器进程中,则运行const fs = require('electron').remote.require('fs')

Then with the fs module you can run a simple exists method on the file: 然后,使用fs模块,您可以在文件上运行一个简单的exist方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM