Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open external file with OS' default application (docx with Word, etc.) using NodeJS and Electron

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.

like image 976
Sommereder Avatar asked Mar 07 '16 09:03

Sommereder


2 Answers

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

like image 103
Artur Carvalho Avatar answered Oct 17 '22 08:10

Artur Carvalho


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

like image 34
Vadim Macagon Avatar answered Oct 17 '22 08:10

Vadim Macagon