用 Electron 打开外部文件 [英] Open external file with Electron

查看:15
本文介绍了用 Electron 打开外部文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在运行的 Electron 应用程序,到目前为止运行良好.对于上下文,我需要运行/打开一个外部文件,该文件是一个 Go-lang 二进制文件,它将执行一些后台任务.基本上,它将充当后端并公开 Electron 应用程序将使用的 API.

I have a running Electron app and is working great so far. For context, I need to run/open a external file which is a Go-lang binary that will do some background tasks. Basically it will act as a backend and exposing an API that the Electron app will consume.

到目前为止,这就是我所了解的:

So far this is what i get into:

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

  • I tried to open the file with the "node way" using child_process but i have fail opening the a sample txt file probably due to path issues.

Electron API 公开了一个 open-file 事件,但它缺少文档/示例,我不知道它是否有用.

The Electron API expose a open-file event but it lacks of documentation/example and i don't know if it could be useful.

就是这样.如何在 Electron 中打开外部文件?

That's it. How i open an external file in Electron ?

推荐答案

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

There are a couple api's you may want to study up on and see which helps you.

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

The fs module allows you to open files for reading and writing directly.

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 模块允许您在一种平台无关的方式.

path

The path module allows you to build and parse paths in a platform agnostic way.

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

外壳

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

shell

The shell api is an electron only api that you can use to shell execute a file at a given path, which will use the OS default application to open the file.

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');

子进程

假设您的 golang 二进制文件是可执行文件,那么您将使用 child_process.spawn 调用它并与之通信.这是一个节点 API.

child_process

Assuming that your golang binary is an executable then you would use child_process.spawn to call it and communicate with it. This is a node api.

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

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

插件

如果您的 golang 二进制文件不是可执行文件,那么您需要制作一个 本机插件包装.

这篇关于用 Electron 打开外部文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆