denislexic
denislexic

Reputation: 11352

Electron open file/directory in specific application

I'm building a sort of File explorer / Finder using Electron. I want to open some file types with a specific application.

I've tried the approach from this answer: Open external file with Electron

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

But when I do that, I get a EACCES error as follows.

Is this the right approach? If yes, how can I fix the issue? If not, what is the right approach?

Upvotes: 38

Views: 49050

Answers (3)

katinas
katinas

Reputation: 442

While the accepted answer does say how to open the folder in file explorer, it doesn't answer the question on how to open the folder WITH an external program like VSCode. It can be done like so:

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

This will launch the folder in VSCode as it's root directory. Code is taken from this repository.

Note: this may require some tinkering depending on what program you are trying to use, but so far it worked properly with: VSCode, Visual Studio 2019, Intellij IDEA, NetBeans.

Upvotes: 3

sawa
sawa

Reputation: 2050

You can open a file or folder through shell commands from the electron module. The commands work on both main and renderer process.

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.

More info on https://github.com/electron/electron/blob/master/docs/api/shell.md

Upvotes: 93

Jabed
Jabed

Reputation: 188

For display native system dialogs for opening and saving files, alerting, etc. you can use dialog module from electron package.

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

A very prompt explanation is provided at Electron Docs.

Upvotes: 0

Related Questions