Sommereder
Sommereder

Reputation: 924

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.

Upvotes: 11

Views: 17728

Answers (2)

Artur Carvalho
Artur Carvalho

Reputation: 7167

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

Upvotes: 1

Vadim Macagon
Vadim Macagon

Reputation: 14847

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

Upvotes: 31

Related Questions