【问题标题】:Electron open file/directory in specific applicationElectron 在特定应用程序中打开文件/目录
【发布时间】:2017-10-14 22:24:30
【问题描述】:

我正在使用 Electron 构建一种文件浏览器/查找器。 我想用特定的应用程序打开一些文件类型。

我已经尝试过这个答案的方法: Open external file with Electron

import { spawn } from 'child_process'
spawn('/path/to/app/superApp.app', ['/path/to/file'])

但是当我这样做时,我得到一个EACCES 错误,如下所示。

这是正确的方法吗?如果是,我该如何解决这个问题?如果没有,正确的方法是什么?

【问题讨论】:

    标签: node.js electron


    【解决方案1】:

    虽然接受的答案确实说明了如何在文件资源管理器中打开文件夹,但它没有回答有关如何打开文件夹 WITH 像 VSCode 这样的外部程序的问题。可以这样做:

    import { spawn, SpawnOptions } from "child_process";
    import { pathExists } from "fs-extra";
    
    const editorPath = "C:/Program Files/Microsoft VS Code/Code.exe";
    
    export const launchExternalEditor = async (
      folderPath: string
    ): Promise<void> => {
      const exists = await pathExists(editorPath);
      if (!exists) {
        console.error("editor not found");
      }
    
      const opts: SpawnOptions = {
        // Make sure the editor processes are detached from the Desktop app.
        // Otherwise, some editors (like Notepad++) will be killed when the
        // Desktop app is closed.
        detached: true,
      };
    
      spawn(editorPath, [folderPath], opts);
    };
    

    这将在 VSCode 中启动文件夹,因为它是根目录。代码取自repository

    注意:这可能需要一些修改,具体取决于您尝试使用的程序,但到目前为止,它可以正常工作:VSCode、Visual Studio 2019、Intellij IDEA、NetBeans。

    【讨论】:

      【解决方案2】:

      您可以通过电子模块中的 shell 命令打开文件或文件夹。这些命令适用于主进程和渲染器进程。

      const {shell} = require('electron') // deconstructing assignment
      
      shell.showItemInFolder('filepath') // Show the given file in a file manager. If possible, select the file.
      shell.openPath('folderpath') // Open the given file in the desktop's default manner.
      

      更多信息https://github.com/electron/electron/blob/master/docs/api/shell.md

      【讨论】:

      • 你也可以试试shell.showItemInFolder('filepath')打开文件夹选择文件
      • 我认为最初的问题是如何在特定应用程序中打开文件。例如:在“Visual Studio Code”中打开一个 .css 文件,而不是在默认应用程序中打开,可能是“Text Edit”。
      • 我相信你是正确的@FlorianSchulz。我用最初提供的链接(并被原始提问者接受)更新了接受的答案。也就是说,我不相信这个答案实际上回答了所提出的问题。
      【解决方案3】:

      要显示用于打开和保存文件、警报等的本机系统对话框,您可以使用电子包中的 dialog 模块。

      const electron = require('electron');
      var filePath = __dirname;
      console.log(electron.dialog.showOpenDialog)({
        properties:['openFile'],
        filters:[
          {name:'Log', extentions:['csv', 'log']}
        ]
      });
      

      Electron Docs 提供了非常及时的解释。

      【讨论】:

        猜你喜欢
        • 2018-10-30
        • 2017-02-19
        • 2017-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-03
        相关资源
        最近更新 更多