NodeJS Electron with express

2019-02-05 09:44发布

问题:

I'm trying to make a webapplication using electron (for the website and desktop application) and express (for sessions etc.)

Now, I got this as my app.js:

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

exp = express();
exp.set('views', __dirname + '/views/');
exp.use(express.static(process.cwd() + '/views'));
exp.get('/', function(req, res) {
    res.render('index', {});
});

function onAppReady() 
{
    mainWindow = new BrowserWindow({
        width: 1080,
        height: 720,
        autoHideMenuBar: true,
        useContentSize: true,
        resizable: false
    });

    mainWindow.loadURL('http://localhost:5000/');
    mainWindow.focus();
    mainWindow.webContents.openDevTools();
}

app.on('ready', onAppReady);

Now, there's a few problems:

  1. If I use node app.js, I get this error: Line: app.on('ready', onAppReady);

    TypeError: Cannot read property 'on' of undefined at Object. (/home/josh/chat_program/client/app.js:26:4) at Module._compile (module.js:571:32) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:488:32) at tryModuleLoad (module.js:447:12) at Function.Module._load (module.js:439:3) at Module.runMain (module.js:605:10) at run (bootstrap_node.js:420:7) at startup (bootstrap_node.js:139:9) at bootstrap_node.js:535:3

  2. If I use electron ., the application starts, but I don't get either a request or a webpage. All I get is basic HTML without anything (only doctype HTML HEAD and BODY).

I searched for a long time but couldn't find anything.

回答1:

Two things.

First I'd clarify your pathing setup and usage, more like this:

var publicPath = path.resolve(__dirname, '/views');
// point for static assets
app.use(express.static(publicPath));
//view engine setup
app.set('views', path.join(__dirname, '/views/'));

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

Second, I would wrap all my express code into a single file that is a self-executing function, so it runs once when you require it. Such as my express file which I call my app.js file:

(function () {
    'use strict';

    var express = require('express');
    var path = require('path');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    var routes = require('./routes.js');

    var app = express();
    var publicPath = path.resolve(__dirname, '../dist');
    var port = 3000;

    // point for static assets
    app.use(express.static(publicPath));

    //view engine setup
    app.set('views', path.join(__dirname, '../dist'));
    app.engine('html', require('ejs').renderFile);
    app.set('view engine', 'html');

    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
        extended:true
    }));

    app.use('/', routes);

    app.use(cookieParser());

    var server = app.listen(port, function () {
        console.log('Express server listening on port ' + server.address().port);
    });

    module.exports = app;

}());

Then in my main file (which I call main.js not app.js, in my case), I instantiate the app and the express server as follows:

var app = require('electron').app;
var Window = require('electron').BrowserWindow; // jshint ignore:line
var Tray = require('electron').Tray; // jshint ignore:line
var Menu = require('electron').Menu; // jshint ignore:line
var fs = require('fs');

var server = require('./ServerSide/app');

var mainWindow = null;

app.on('ready', function () {
    'use strict';

    var path = require('path');
    var iconPath = path.resolve(__dirname, './dist/myicon.ico');
    const appIcon = new Tray(iconPath);
    mainWindow = new Window({
        width: 1280,
        height: 1024,
        autoHideMenuBar: false,
        useContentSize: true,
        resizable: true,
        icon: iconPath
        //  'node-integration': false // otherwise various client-side things may break
    });
    appIcon.setToolTip('My Cool App');
    mainWindow.loadURL('http://localhost:3000/');

    // remove this for production
    var template = [
        {
            label: 'View',
            submenu: [
                {
                    label: 'Reload',
                    accelerator: 'CmdOrCtrl+R',
                    click: function(item, focusedWindow) {
                        if (focusedWindow) {
                            focusedWindow.reload();
                        }
                    }
                },
                {
                    label: 'Toggle Full Screen',
                    accelerator: (function() {
                        if (process.platform === 'darwin') {
                            return 'Ctrl+Command+F';
                        } else {
                            return 'F11';
                        }
                    })(),
                    click: function(item, focusedWindow) {
                        if (focusedWindow) {
                            focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
                        }
                    }
                },
                {
                    label: 'Toggle Developer Tools',
                    accelerator: (function() {
                        if (process.platform === 'darwin') {
                            return 'Alt+Command+I';
                        } else {
                            return 'Ctrl+Shift+I';
                        }
                    })(),
                    click: function(item, focusedWindow) {
                        if (focusedWindow) {
                            focusedWindow.toggleDevTools();
                        }
                    }
                },
            ]
        }
    ];

    var menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);

    mainWindow.focus();

});

// shut down all parts to app after windows all closed.
app.on('window-all-closed', function () {
    'use strict';
    app.quit();
});

Note that I am using this with success on Windows platform, so small tweaks may be needed for any platform specific items listed in this example.