Home > Enterprise >  Can I “listen” for a specific output with child_process?
Can I “listen” for a specific output with child_process?

Time:09-26

So far I have gotten my script to execute a windows .bat file with child_process, my issue is that it opens it in the background with no way to “connect” to it to see what happens and debug, is there a way to “listen” for a certain output to happen? For example, if the .bat outputs a “Done!” in the shell at one point, is there a way to make my node.js script detect that certain keyword and run further commands if it does?

Thanks!

Some clarification: The .bat outputs "Done!" and stays running, it doesn't stop, all I want to do is detect that "Done!" so that I can send a message to the user that the server has successfully started

My current code:

exec('D:\\servers\\game_server_1\\start.bat', {shell: true, cwd: 'D:\\servers\\game_server_1'});

CodePudding user response:

Well, if you're trying to do a one and done type of NodeJS script, you can just spawn a process that launches with the given command and exits when all commands completed. This creates a one and done streaming interface that you can monitor. The stdout returns a data buffer that returns the command you ran, unless it's something like START to launch a program-- it returns null. You could just issue a KILL command after the START -- your_program.exe:

const spawn = require('child_process').spawn;
const child = spawn('cmd.exe', ['/c', 'commands.bat']);
let DONE = 0;
const done = () => {
  console.log("log it");
  DONE  ;
};
child.stdout.on('data', function (data) {
  console.log('stdout: '   data);
  //it's important to add some type of counter to 
  //prevent any logic from running twice, since
  //this will run twice for any given command

  if ( data.toString().includes("DONE") && DONE === 0 ) {
    done();
  }
});

child.stderr.on('data', function (data) {
  console.log('stderr: '   data);
});

child.on('exit', function (code) {
  console.log('child process exited with code '   code);
});

Keep in mind, when you run a command to launch a program and the program launches, the data buffer will be null in stdout event listener. The error event will only fire if there was an issue with launching the program.

YOUR .BAT:

ECHO starting batch script

//example launching of program
START "" https://localhost:3000

//issue a command after your program launch
ECHO DONE

EXIT

You could also issue an ECHO DONE command right after the command where you launched the program and listen for that, and try and parse out that command from stdout.

CodePudding user response:

You could use a Regular expression.

const { spawn } = require('child_process');
const child = spawn(...);

child.stdout.on('data', function (data) {
  console.log('stdout: '   data);
  // Now use a regular expression to detect a done event
  // For example 
  data.toString().match(/Done!/);
});

// Error handling etc. here
  • Related