Search code examples
javascriptjsonelectronelectron-packager

Call Backend Using electron


So, I am making a small desktop application using electron and P5 (for front-end). I wanna make the application fully working while offline meaning I want to store the data locally instead of using a database. However I cannot change the json files on the frontend meaning I need to somehow call the backend (the main file of the application) from the front-end. Since I am kinda new to electron could anyone tell me how could I make a button call a function on the main file? I spent a way too much time searching for a solution online but was unable to find any.


Solution

  • You need to enable nodeIntegration, then you can use the built-in node process via electron remote module.

    So, in your main.js enable the nodeIntegration:

    app.on('ready', () => {
        mainWindow = new BrowserWindow({
            // ...
            webPreferences: {
                nodeIntegration: true,
            }
            // ...
        });
    });
    

    Now you can use electron remote module wherever you want and make file operations via the fs module:

    const { remote } = require('electron');
    const fs = remote.require('fs');
    
    fs.writeFile('ourDataStorage.txt', data, (err) => {
       if (err) throw err;
       console.log('File has been saved.');
    });