Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
896 views
in Technique[技术] by (71.8m points)

javascript - Why can't you read package.json in a builded electron app?

Hello Stackoverflow users!

I am trying to place all of the configuration for the electron app in the package.json file.

Here is my code snippet:
index.js

const { app, BrowserWindow, ipcMain } = require('electron');
const fs = require('fs');

function readConf() {
  const data = fs.readFileSync('./package.json', 'utf8');
  return data;
}

ipcMain.on('synchronous-message', (event, arg) => {
  event.returnValue = readConfig();
})

index.html

<script type="text/javascript">
const { ipcRenderer } = require('electron')
config = JSON.parse(ipcRenderer.sendSync('synchronous-message', ''))
</script>
<h1>Version of <script>document.write(config.name)</script> is <script>document.write(config.version);</script></h1>

The code is working when you run the app via npm start, but when you make it into an exe with electron-forge and squirrel (npm make) and try to run it after installing it throws an error that the package.json file can't be found. So what do you need to specify as the path to the file to read it in the built app?

I am using electron forge.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I found a way to fix the issue!

Instead of

const data = fs.readFileSync('./package.json', 'utf8');

You'll need to write

const data = fs.readFileSync(__dirname + '/../package.json', 'utf8');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...