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

Issue

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.

Solution

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

Answered By – sinmineryt

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.