10

I'm using NodeJS/Electron for a desktop app.

What I wanna do, is to open a file with it's OS' default application, like .docx with Word.

What I tried so far are approaches using child_process.spawn, .exec or .execFile but I don't get anything.

Here is my actual code:

var fs = require('fs'),
    cp = require('child_process');

cp.spawn(__dirname + '/test.docx');

Thanks in advance.

Sommereder
  • 904
  • 4
  • 10
  • 32
  • Answered here already: http://stackoverflow.com/a/29917107/5334137 – leroydev Mar 07 '16 at 10:00
  • I arrived here and missed the question was Electron-specific. The accepted solution will only work inside an Electron app. There is a separate question for Node.js in general, outside of an Electron app: https://stackoverflow.com/q/8500326/62269 – Bluu Jun 11 '18 at 22:42

2 Answers2

29

Use the openItem() function provided by Electron's shell module, for example:

const shell = require('electron').shell;
const path = require('path');

shell.openItem(path.join(__dirname, 'test.docx'));

According to the docs the shell module should be available in both the main/browser and renderer processes.

Note: Electron 9.0.0 The shell.openItem API has been replaced with an asynchronous shell.openPath API. shell.openPath docs

Alex
  • 59,571
  • 22
  • 137
  • 126
Vadim Macagon
  • 14,463
  • 2
  • 52
  • 45
  • Can we get a closed signal ? Is there a call back where I would know application was closed ? – django Aug 04 '16 at 16:44
  • 2
    @django No, this is a fire and forget sort of thing. If you want to detect if an external application has closed you'll need to spawn it using [child_process.spawn](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_child_process_spawn_command_args_options). – Vadim Macagon Aug 05 '16 at 03:24
  • @VadimMacagon I have been trying ```ls.on('close'``` event but it gets fired as soon as ms word is opened. Can you please post example or should i create another question for it ? – django Aug 05 '16 at 07:09
  • Is it possible to show apps/softwares that can open the file, instead of opening it in default app. Example svg file opens in browser by default. I want to let the user choose another app like notepad or other code editor etc. Is that possible? – 27px Jun 26 '21 at 12:23
1

Adding here the snippet for newer electron versions (9+) and imports:

import { shell } from 'electron';
import path from 'path';

shell.openPath(path.join(__dirname, 'test.docx'));

Artur Carvalho
  • 6,901
  • 10
  • 76
  • 105