11

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.

2
  • Answered here already: stackoverflow.com/a/29917107/5334137 Commented Mar 7, 2016 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: stackoverflow.com/q/8500326/62269 Commented Jun 11, 2018 at 22:42

2 Answers 2

31

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

Sign up to request clarification or add additional context in comments.

4 Comments

Can we get a closed signal ? Is there a call back where I would know application was closed ?
@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.
@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 ?
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?
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'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.