Electron:使用参数运行shell命令

16

我正在构建一款Electron应用程序,

使用Shell API(https://electronjs.org/docs/api/shell)可以轻松运行shell命令。

例如,以下命令可以完美运行:

shell.openItem("D:\test.bat");

这个不行

shell.openItem("D:\test.bat argument1");

如何使用参数运行电子外壳命令?
1个回答

21

shell.openItem 不是为此而设计的。
使用 NodeJS 的 child_process 核心模块中的 spawn 函数。

let spawn = require("child_process").spawn;

let bat = spawn("cmd.exe", [
    "/c",          // Argument for cmd.exe to carry out the specified script
    "D:\test.bat", // Path to your file
    "argument1",   // First argument
    "argumentN"    // n-th argument
]);

bat.stdout.on("data", (data) => {
    // Handle data...
});

bat.stderr.on("data", (err) => {
    // Handle error...
});

bat.on("exit", (code) => {
    // Handle exit
});

需要安装Node还是只需要npm依赖? - Slimane Deb
我的意思是,“child_process”只是Electron JS的一部分,也就是说,我不需要在客户端桌面安装Node.js吗? - Slimane Deb
3
child_process 是 NodeJS 的一部分,而不是 Electron。它是一个核心模块。请参见这里 - NullDev
1
@SlimaneDeb,为了澄清NullDev的说法,electron默认在其二进制文件中捆绑了nodejs。因此,所有核心模块都应该对您可用。 - Samarth Ramesh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接