Launch Express server from an Electron app

The goal is to launch an Express server after initializing an Electron app. The execution process is:

main.jsindex.htmlserver.js

Set the app

An Electron app has a default main.js:

javascript
const { app, BrowserWindow } = require('electron');

function createWindow () {
    
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          nodeIntegration: true
        }
    });

    win.loadFile('index.html');
    
}

app.whenReady().then(createWindow);

The Electron app loads index.html:

HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset = 'UTF-8'>
    <script src = './src/server.js'></script>
</head>
<body>
    <h1>Application Electron and Express</h1>
</body>
</html>

You can load server.js from the HTML file to start an Express server on the background:

javascript
const express     = require('express');
const ffmpegPath  = require('ffmpeg-static');
Stream            = require('node-rtsp-stream');

let app = express();

let server = app.listen(3000);

app.get('/', function(req, res){
   
    res.send('Server is ready!');
    
});

Run the app

At this point, you can run the Electron app:

terminal
npm run start

Electron will open a window with "Application Electron and Express" as a title. The Express server will run on the background.

To check if the server is active, open your browser and go to http://localhost:3000. You will see a message: "Server is ready!"

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.