简体   繁体   中英

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. 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. In Javascript however, I'm always given the following:

Output

Error: find: '/I': No such file or directory find: '/N': No such file or directory

Error: find: "chrome.exe": No such file or directory

Program is not running

Child exited with code 0

renderer.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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