You can run your Express app very easily inside your Electron app.
All you need to do is to:
- place all the files of your Express app inside a new app folder in
your_electron_app\resources\app
- reconfigure the
app.js
file - refactor some relative pathes in your Express app
You should start your Express app before opening a new BrowserWindow and the load a new mainWindow like this:
const express = require('./express'); //your express app
app.on('ready', function() {
express();
mainWindow = new BrowserWindow({
width: 1280,
height: 720,
autoHideMenuBar: true,
useContentSize: true,
resizable: false,
});
mainWindow.loadURL('http://localhost:5000/');
mainWindow.focus();
});
Pathes in Electron don't work the same way they do in your Express app.
You have to make them all from relative to absolute pathes first.
So instead of doing this:
app.set('views', '/client/views');
app.use(express.static(/client/dist/static));
you have to do this:
app.set('views', __dirname + '/client/views');
app.use(express.static(__dirname + '/client/dist/static'));
The problem with this approach is that you are putting your Express server on the same process as the Electron main process (while the browser window is on the render process). This is fine for very simple apps that have no significant work on the server side, other than pushing a few files to the browser. But it will absolutely hang the main process (which manages the electron shell, border and menus) when you have significant server work going on.
This is not a solution if you have any strenuous work to be done in your express server. This is ironic, and basically an antagonistic way of using Electron, since it goes against the architecture of node. That is, by running the server inline with the electron main process (the express server could be doing anything such as file conversions, extensive i/o, etc : basically anything blocking), you are running electron against what is normally a primary benefit of using nodejs at all-- to run I/O calls as async so that you don't hang on such requests.
If you are going to spin up a server in Electron, you should do so on another process.. not run that server on the main Electron process, or its render process. You should launch a separate process for your server (spawn/exec/execFile or a new BrowserWindow loaded as headless, I suppose), so it is unhinged from your Electron operation. That all said, there are very few concise and clear examples of proper use of any of these separate process launchers working- at least, I can find few that work for this application that run on Windows. Most of the examples out there seem to run well on Linux, but not on Windows. One article online (at https://blog.axosoft.com/2016/03/04/electron-things-to-know/ ) suggests using the
var backgroundWindow = new BrowserWindow({show: false})
approach , but this is not clear how to run a server script in a browser window (even headless) context.