1

I have a command telnet that recives as parameter an IP and Port, and it gets a log from a remote program while running. What I'm doing: node will create a process telnet, filter the log for some informations and try to rerun telnet in case it closes. At first time it runs nicely, but when the I close the remote program, node desn't try rerun telnet.

'use strict';

const { spawn } = require( 'child_process' );
const cmd = 'telnet';
const params = ['10.10.10.10', '1010'];
var telnet;

let isRunning = false;

connect();
connectionCheckRoutine()

telnet.stdout.on( 'data', data => {
  console.log( `> ${data}` );
  isRunning = true;
} );

telnet.stderr.on('data', data => {
  console.log(`err: ${data}` );
} );

telnet.on('close', code => {
  console.log( `child process exited with code ${code}` );
  isRunning = false;
} );

function connect(){
  telnet = spawn( cmd, params);
}

async function connectionCheckRoutine(){
  while(true){
    await sleep(5000);
    if(!isRunning){
      console.log('Reconnecting...');
      connect();
    }
  }
}

async function sleep(millis) {
    return new Promise(resolve => setTimeout(resolve, millis));
}

I expected that after process ends I could try reconnect using the child_process.spawn() again, but nothing happens if I call spawn() once more.

1 Answer 1

1

The issue happens because the event listeners that you register for the child process events do not re-register when telnet variable is overwritten with a new child process.

Try to move the event handlers registration inside the connect function to ensure that the handlers are re-registered every time a child process is spawned:

function connect(){
  const telnet = spawn(cmd, params);

  telnet.stdout.on( 'data', data => {
    console.log( `> ${data}` );
    isRunning = true;
  });

  telnet.stderr.on('data', data => {
    console.log(`err: ${data}` );
  });

  telnet.on('close', code => {
    console.log( `child process exited with code ${code}` );
    isRunning = false;
  });
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.