Running node.js servers on local user's machine when packaged with electron

16 views Asked by At

I have been running into some problem relating to running my node.js servers locally upon electron app instantiation after running electron-packager.

The servers used to start fine when I was just running npm run electron in development mode, which would start both my servers and my frontend into electron. However, as soon as packaged, the frontend did render, however, the servers did not. I have been battling with this for some time now and am looking for any potential solutions to the problem.

I have tried a couple of things from changing the path from a hardcoded path to __dirname , ''. I have also looked into child_processes and by also using the preload.js script to start it that way, however unsuccessful.

here is snippets of my main.js file that use to take care of this process and gracefully shut it down:

const { app, BrowserWindow, ipcMain, screen } = require('electron');
const { fork } = require('child_process');
const Store = require('electron-store');
const path = require('path');
require('dotenv').config();


const win = new BrowserWindow({
    width: width,
    height: height,
    title: "Terrafai",
    icon:'./client/src/assets/Emblem_Jira.png',
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: false, // Set this to false for security
      contextIsolation: true,  // Ensure this is true
      webSecurity: true,       // It's better enabled unless there's a specific reason
    },
  });

  win.loadFile('electron/src/client/dist/index.html');

};

app.whenReady().then(() => {
  const serverPath = path.join(__dirname, 'server.js');
  const backendServer1 = fork(serverPath);

  const authServerPath = path.join(__dirname, 'authServer.js');
  const backendServer2 = fork(authServerPath);

  backendServer1.on('error', (err) => { console.error('Backend Server 1 Error:', err); });
  backendServer2.on('error', (err) => { console.error('Backend Server 2 Error:', err); });

  // setupTokenManagementIPC(); // Set up IPC handlers
  createWindow();

  app.on('before-quit', () => {
    console.log("servers are shutting down...");
    backendServer1.kill('SIGINT');
    backendServer2.kill('SIGINT');
  });
});
0

There are 0 answers