如何使电子可执行文件从同一构建目录中读取[json]文件

时间:2019-08-30 14:42:53

标签: javascript node.js electron electron-builder electron-packager

构建我的电子应用程序并运行electron.exe之后,我希望我的应用程序在加载之前首先读取config.json文件。 在这一点上我不知道: 建立我的电子应用程序时如何生成该文件 如何使我的应用在加载时首先读取config.json文件 以及如何调试电子可执行文件。

请您帮忙。

1 个答案:

答案 0 :(得分:0)

我做了类似的事情,我读了main.js内部的文件(在我的情况下为configuration.json),然后使用ipcRenderer将数据传递给preload.js。

Main.js

function getUrlByFile() {
  let content = "{\n\t \"url\" : \"https://github.com/claudeth1919/WrapperForm\"\n}";

  try {
    console.log(__dirname + '\\configuration.json');
    if (!fs.existsSync(__dirname + '\\configuration.json')) {
      fs.writeFileSync('configuration.json', content, 'utf-8');
    }
  }
  catch (e) {
    console.log('Failed to create the file !');
  }

  fs.readFile(__dirname + "\\configuration.json", "utf-8", (err, data) => {
    if (err) {
      console.log("error reading file");
      return;
    }
    let json = JSON.parse(data)
    console.log(json.url);
    setUrl(json.url);
  })
}


function setUrl(url){
  ipcMain.on('get-url', (event, arg) => {
    console.log("url request");
    event.returnValue = url
  })
}

preload.js

window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  } 

  const { ipcRenderer } = require('electron')
  let url = ipcRenderer.sendSync('get-url', null);
  console.log(url);
  var webview = document.getElementById('wrapper');
  if(url==''||url==undefined){
    webview.src = "https://github.com/claudeth1919/WrapperForm";
  }
  webview.src = url;

  for (const type of ['chrome', 'node', 'electron']) {
    replaceText(`${type}-version`, process.versions[type])
  }
})

我与您分享我的项目:https://github.com/claudeth1919/WrapperForm

我希望它能对您有所帮助。问候