如何在现有Express应用程序中使用Electron

时间:2018-11-16 23:11:34

标签: node.js electron

我在https://github.com/frankhale/electron-with-express上阅读并尝试了类似的示例,但我仍然不明白如何将Express应用转换为Electron

如何在现有Express应用程序中使用Electron?

以这个Express应用程序为例:

app.js

var express = require("express");
var app = express();

var request = require("request");

app.set("view engine", "ejs");

app.get("/", function(req, res) {
    res.render("search");
});

app.get("/results", function(req, res){
    var query = req.query.search;
    var url = "https://yts.am/api/v2/list_movies.json?sort=seeds&limit=15&query_term='" + query + "'";
    request(url, function(error, response, body){
        var data = JSON.parse(body);
        if(!error && response.statusCode == 200){
            //res.send(data["data"]["movies"][0]["title"]);
            res.render("results", {data: data});
            //["movies"][0]["title"]
        }
        else
        console.log(data);
    });
});

app.listen(process.env.PORT, process.env.IP, function(){
    console.log("IMDB server has started");
});

search.ejs

Search for a movie

<form action="results" method="GET">
    <input type="text" placeholder="search term" name="search">
    <input type="submit">
</form>

results.ejs

Results page
<ul>
    <% data["data"]["movies"].forEach(function(movie){ %>
        <li>
            <strong><%= movie["title"]%></strong> - <%= movie["year"]%>
        </li>
    <% }) %>
</ul>

<a href="/">Search again</a>

1 个答案:

答案 0 :(得分:5)

在电子main.js文件中,您应该require文件app.js以启动Express应用程序,然后创建一个新的BrowserWindow实例并加载您Express应用程序正在监听。

请注意,您将不得不在Electron中对IP和PORT进行硬编码,或者从Express中导出它们并将其导入到Electron main.js脚本中。

./ main.js

const { BrowserWindow, app } = require('electron')
require('./app.js')

let mainWindow = null

function main() {
  mainWindow = new BrowserWindow()
  mainWindow.loadURL(`http://localhost:3000/`)
  mainWindow.on('close', event => {
    mainWindow = null
  })
}

app.on('ready', main)

./ package.json

{
  "name": "your-app-name",
  "version": "1.0.0",
  "description": "A description of your application",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "repository": "https://github.com/link/to/repo",
  "keywords": [ "some","keywords" ],
  "author": "You",
  "license": "Your License",
  "dependencies": {
    "ejs": "^2.6.1", // required for your specific example where `ejs` package is used
    "electron": "^3.0.9",
    "express": "^4.16.4"
  }
}

然后,您要确保node_modules目录与main.jspackage.json在同一目录中。

最后,您可以使用以下命令启动Express / Electron应用程序:

> npm start

如果您的Express应用程序与Electron不在同一目录中,则必须设置views的Express目录:

app.js

var path = require('path')
var request = require("request");
var express = require("express");
var app = express();

app.set('views', path.join(__dirname, '/views'));

...

/views是相对于app.js的目录,其中包含您的视图。