'How to read config file in electronjs app

It's my first time using Electron JS and nodejs. I've built a small app that reads some records from a database and updates them. Everything is working fine. I have a config file with the database credentials but when I build a portable win app, I cannot figure out how to read the config file that I would like to place next to the exe. I would like to have easy access to the file, so I could run the same app on different databases.

Can anyone tell me if what I want is possible and how? I already tried to get the exe location but I couldn't. I also read a lot of topics here but nothing seems to solve my problem (I might be doing something wrong).

I'm using electron-builder to build my app.

Thanks in advance.

Edit #1

My Config file is

{
    "user" :"X",
    "password" :"X",
    "server":"X",
    "database":"X",
    "options":
    {
        "trustedconnection": true,
        "enableArithAbort" : true,
        "trustServerCertificate": true
    }
}

This is what I've and works when I run the project with npm start

const configRootPath = path.resolve(__dirname,'dbConfig.json');
dbConfig = JSON.parse(fs.readFileSync(configRootPath, { encoding: 'utf-8' }));

However, when I build it, the app is looking for the file in another location different from the one where the executable is.



Solution 1:[1]

Use of Electron's app.getPath(name) function will get you the path(s) you are after, irrespective of which OS (Operating System) you are using.

Unless your application writes your dbConfig.json file, it may be difficult for your user to understand exactly where they should place their database config file as each OS will run and store your application data in a different directory. You would need to be explicit to the user as to where to place their config file(s). Alternatively, your application could create the config file(s) on the user's behalf (automatically or through a html form) and save it to a location 'known' to the application.

A common place where application specific config files are stored is in the user's application data directory. With the application name automatically amended to the directory, it can be found as shown below.

const electronApp = require('electron').app;

let appUserDataPath = electronApp.getPath('userData');

console.log(appUserDataPath );

In your use case, the below would apply.

const electronApp = require('electron').app;

const nodeFs = require('fs');
const nodePath = require('path');

const configRootPath = nodePath.join(electronApp.getPath('userData'), 'dbConfig.json');

dbConfig = JSON.parse(nodeFs.readFileSync(configRootPath, 'utf-8'));

console.log(configRootPath);
console.log(dbConfig);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 midnight-coding