使用Electron打开外部文件

Jav*_*diz 30 electron

我有一个正在运行的Electron应用程序,到目前为止工作得很好.对于上下文,我需要运行/打开一个外部文件,这是一个Go-lang二进制文件,它将执行一些后台任务.基本上它将作为后端并暴露电子应用程序将消耗的API.

到目前为止,这是我进入的:

  • 我尝试使用child_process以"节点方式"打开文件,但是由于路径问题,我无法打开示例txt文件.

  • Electron API暴露了一个开放文件事件,但缺少文档/示例,我不知道它是否有用.

而已.我如何在Electron中打开外部文件?

jus*_*ase 59

你可能想要研究几个api,看看哪个有帮助你.

FS

fs模块允许您直接打开文件进行读写.

var fs = require('fs');
fs.readFile(p, 'utf8', function (err, data) {
  if (err) return console.log(err);
  // data is the contents of the text file we just read
});
Run Code Online (Sandbox Code Playgroud)

路径

path模块允许您以平台无关的方式构建和解析路径.

var path = require('path');
var p = path.join(__dirname, '..', 'game.config');
Run Code Online (Sandbox Code Playgroud)

贝壳

shellAPI是一个电子只是你可以用它来壳在给定的路径,这将使用操作系统默认的应用程序打开的文件执行文件API.

const {shell} = require('electron');
// Open a local file in the default app
shell.openItem('c:\\example.txt');

// Open a URL in the default way
shell.openExternal('https://github.com');
Run Code Online (Sandbox Code Playgroud)

child_process

假设您的golang二进制文件是可执行文件,那么您将使用child_process.spawn它来调用它并与之通信.这是一个节点api.如果你的golang二进制文件不是可执行文件,那么你需要制作一个原生的插件包装器.

var path = require('path');
var spawn = require('child_process').spawn;

var child = spawn(path.join(__dirname, '..', 'mygoap.exe'), ['game.config', '--debug']);
// attach events, etc.
Run Code Online (Sandbox Code Playgroud)

  • 看来 shell.openItem 已更改为 shell.openPath (8认同)

phi*_*hil -2

我知道这并不完全符合您的规范,但它确实将您的 golang 二进制文件和 Electron 应用程序完全分开。

我的方法是将 golang 二进制文件公开为 Web 服务。像这样

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    //TODO: put your call here instead of the Fprintf
    fmt.Fprintf(w, "HI there from Go Web Svc. %s", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/api/someMethod", handler)
    http.ListenAndServe(":8080", nil)
}
Run Code Online (Sandbox Code Playgroud)

然后,Electron 只需使用 javascript 函数对 Web 服务进行 ajax 调用即可。像这样(你可以使用 jQuery,但我发现这个纯 js 工作得很好)

function get(url, responseType) {
    return new Promise(function(resolve, reject) {
      var request = new XMLHttpRequest();
      request.open('GET', url);
      request.responseType = responseType;

    request.onload = function() {
    if (request.status == 200) {
      resolve(request.response);
    } else {
      reject(Error(request.statusText));
    }
  };

  request.onerror = function() {
    reject(Error("Network Error"));
  };

  request.send();
});
Run Code Online (Sandbox Code Playgroud)

用这种方法你可以做类似的事情

get('localhost/api/somemethod', 'text')
  .then(function(x){
    console.log(x);
  }
Run Code Online (Sandbox Code Playgroud)