首页 文章

使用Electron打开外部文件

提问于
浏览
26

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

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

  • 我试图使用child_process使用child_process打开文件,但是由于路径问题我无法打开示例txt文件 .

  • Electron API公开open-file事件,但它没有文档/示例,我不知道它是否有用 .

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

3 回答

  • -1

    你可能想要研究几个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
    });
    

    路径

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

    var path = require('path');
    var p = path.join(__dirname, '..', 'game.config');
    

    shell

    shell api是一个仅限电子的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');
    

    child_process

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

    var path = require('path');
    var spawn = require('child_process').spawn;
    
    var child = spawn(path.join(__dirname, '..', 'mygoap.exe'), ['game.config', '--debug']);
    // attach events, etc.
    
  • 44

    Electron允许使用 nodejs packages .

    换句话说,导入节点包就像在节点中一样,例如:

    var fs = require('fs');
    

    要运行golang二进制文件,可以使用child_process模块 . 文档是彻底的 .

    Edit :你必须解决路径差异 . open-file 事件是由窗口触发的客户端事件 . 不是你想要的 .

  • 0

    我知道这不完全符合您的规范,但它确实将您的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)
    }
    

    然后从Electron只需使用javascript函数调用web服务 . 像这样(你可以使用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();
    });
    

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

    get('localhost/api/somemethod', 'text')
      .then(function(x){
        console.log(x);
      }
    

相关问题