使用 Node.js 执行 EXE 文件

Execute an EXE file using Node.js

本文关键字:EXE 文件 执行 js Node 使用      更新时间:2023-09-26

我不知道如何在 Node.js 中执行 EXE 文件。这是我正在使用的代码。它不起作用,也不打印任何内容。有没有使用命令行执行 EXE 文件的方法?

var fun = function() {
  console.log("rrrr");
  exec('CALL hai.exe', function(err, data) {
    console.log(err)
    console.log(data.toString());
  });
}
fun();

您可以在 Node.js 中尝试子进程模块的 execFile 函数。

参考: child_process.execFile(file[, args][, options][, 回调])

您的代码应如下所示:

var exec = require('child_process').execFile;
var fun =function(){
   console.log("fun() start");
   exec('HelloJithin.exe', function(err, data) {
        console.log(err)
        console.log(data.toString());
    });
}
fun();

如果要执行的exe位于其他目录中,并且您的exe与它所在的文件夹有一些依赖关系,请尝试在选项中设置cwd参数

var exec = require('child_process').execFile;
/**
 * Function to execute exe
 * @param {string} fileName The name of the executable file to run.
 * @param {string[]} params List of string arguments.
 * @param {string} path Current working directory of the child process.
 */
function execute(fileName, params, path) {
    let promise = new Promise((resolve, reject) => {
        exec(fileName, params, { cwd: path }, (err, data) => {
            if (err) reject(err);
            else resolve(data);
        });
    });
    return promise;
}

文档

如果你使用的是 Node.js 或任何支持 Node 的前端框架.js(React 或 Vue.js)

const { execFile } = require('child_process');
const child = execFile('chrome.exe', [], (error, stdout, stderr) => {
  if (error) {
    throw error;
  }
  console.log(stdout);
});

如果.exe文件位于计算机中的某个位置,请将 chrome.exe 替换为要执行的应用程序的路径例如"C:'Program Files (x86)'Google'Chrome'Application'chrome.exe"

const child = execFile('C:'Program Files (x86)'Google'Chrome'Application'chrome.exe', [], (error, stdout, stderr) => {
  if (error) {
    throw error;
  }
  console.log(stdout);
});

我已经试过了。它有效。

const { exec } = require('child_process');
// Replace 'path/to/your/file.exe' with the actual path to your .exe file
const filePath = 'path/to/your/file.exe';
// Execute the .exe file
exec(filePath, (error, stdout, stderr) => {
  if (error) {
    console.error(`Error executing the .exe file: ${error}`);
    return;
  }
  // Process the output or error messages if needed
  if (stdout) {
    console.log(`Standard output: ${stdout}`);
  }
  if (stderr) {
    console.error(`Standard error: ${stderr}`);
  }
});

你有没有想过在这个过程中使用批处理文件?我的意思是使用 Node 启动一个.bat文件.js这将同时启动一个.exe文件?

只是使用顶部的答案,我得到了这个:

  1. 在 exe 文件的目录中创建一个.bat文件

  2. 输入蝙蝠文件 START <full file name like E:''Your folder''Your file.exe>

  3. 输入您的.js文件: const shell = require('shelljs') shell.exec('E:''Your folder''Your bat file.bat')