使用 NodeJS 和 Electron 使用 OS' 默认应用程序(docx 和 Word 等)打开外部文件

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

我正在使用 NodeJS/Electron 桌面应用程序。

我想做的是用 OS' 默认应用程序打开一个文件,比如用 Word 打开 .docx。

到目前为止,我尝试过使用 child_process.spawn、.exec 或 .execFile 的方法,但我没有得到任何东西。

这是我的实际代码:

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

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

提前致谢。

使用Electron的shell模块提供的openItem()函数,例如:

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

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

根据文档,shell 模块应该在 main/browser 和渲染器进程中都可用。

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

在此处添加较新电子版本 (9+) 的代码段 导入:

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

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