简体   繁体   English

如何通过 CMD.exe 让 NodeJS 子进程运行.bat 文件

[英]How to get NodeJS child process to run .bat file via CMD.exe

I am currently writing an app launcher for Windows using ElectronJS and Javascript for windows.我目前正在为 Windows 使用 ElectronJS 和 Javascript 为 windows 编写应用程序启动器。 I want to block multiple instances of one app opening.我想阻止一个应用程序打开的多个实例。 To do this I have written a batch script that checks if the process is running and if it is, print out a message saying "Program is running" and if it isn't, print "Program is not running".为此,我编写了一个批处理脚本来检查进程是否正在运行,如果是,则打印出一条消息“程序正在运行”,如果不是,则打印“程序未运行”。

Batch Script批处理脚本

echo off
tasklist /FI "IMAGENAME eq chrome.exe" 2>NUL | find /I /N "chrome.exe">NUL
if "%ERRORLEVEL%"=="0" echo Program is running
if "%ERRORLEVEL%"=="1" echo Program is not running

When I run this via cmd.exe it gives me the correct output whether the application is running or not.当我通过 cmd.exe 运行它时,无论应用程序是否正在运行,它都会给我正确的 output。 In Javascript however, I'm always given the following:然而,在 Javascript 中,我总是得到以下信息:

Output Output

Error: find: '/I': No such file or directory find: '/N': No such file or directory错误:查找:'/I':没有这样的文件或目录 查找:'/N':没有这样的文件或目录

Error: find: "chrome.exe": No such file or directory错误:查找:“chrome.exe”:没有这样的文件或目录

Program is not running程序没有运行

Child exited with code 0孩子以代码 0 退出

renderer.js渲染器.js

  const { spawn } = require('child_process');
  const bat = spawn('cmd.exe', ["/c", 'multiScript.bat']);

  bat.stdout.on('data', (data) => {
    console.log(data.toString());
  });

  bat.stderr.on('data', (data) => {
    console.error(data.toString());
  });

  bat.on('exit', (code) => {
    console.log(Child exited with code ${code});
  });

Folder Structure文件夹结构

projectfolder/
|-src/
|    |-renderer.js (File that is trying to spawn the batch file)
|    |-multiScript.bat (The bat file I am trying to execute)

It's because when you are spawning the child process it executes within the directory of your main process.这是因为当您生成子进程时,它会在主进程的目录中执行。 Every path you call should be relative to the file which the child process was spawned or the absolute path of the system.您调用的每个路径都应该相对于生成子进程的文件或系统的绝对路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM