运行 来自 JS 函数内部的命令行(使用 Electron.js)

Run a command line from inside a JS function (using Electron.js)

我正在使用 Electron 构建一个销售点应用程序。 在程序的某些时候,我需要打开收银机。 这可以通过将 ECHO>COM3 放入我的 Windows 计算机上的命令提示符或通过打开包含该命令的 .bat 文件来完成。我以前使用 PHP 打开有效的文件,但我不想使用 PHP 因为它必须在我想使用该程序的每台计算机上安装和配置上。

如果我像这样创建一个 javascript 函数

function openCashDrawer(){

}

我可以在函数中放入什么来执行我的一行代码?听起来很简单,但我已经在网上搜索并尝试了很多东西,但没有任何效果。我认为有一种方法可以通过 node.js 完成,但我不知道它是如何工作的。

我的 main.js 文件中确实设置了 nodeIntegration: true

这是我的 package.json 文件

{
  "name": "elec",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "start": "electron main.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "electron": "^15.3.0"
  }
}

这可以通过在 Node.js 中执行 shell 命令来实现,为此可以使用 child_process 模块中的 exec() 函数。

正在导入child_process

为了将 Node 模块与 electrion 一起使用,首先需要启用节点集成以及远程模块,这可以在 webPreferences 中这样设置:

webPreferences: {
    nodeIntegration: true,
    contextIsolation: false,
    enableRemoteModule: true
}

使用以下代码,您可以执行 shell 命令并在需要时处理来自标准输出的响应。

const { exec } = require("child_process");

function openCashDrawer() {
    exec("ECHO>COM3", (error, stdout, stderr) => {
    if (error) {
        console.log(`[ERROR] openCashDrawer: ${error.message}`);
        return;
    }
    
    if (stderr) {
        console.log(`[STDERROR] openCashDrawer: ${stderr}`);
        return;
    }

    console.log(`openCashDrawer: ${stdout}`); // Output response from the terminal
    });
}

处理权限不足

通过 Node.js 执行 shell 命令需要提升才能以正确的权限执行。在Windows上,这是为了能够以管理员身份执行,解决方法是调整Node应用程序具有相应的权限,使其能够执行shell命令。