0

I have the below code

const { readFileSync } = require('fs');

const { Client } = require('ssh2');

// console.log(filename)

const conn = new Client();
conn.on('ready', () => {
     
    console.log('Client :: ready');
    console.log("We will execute the file " + filename);
  conn.exec('python ~/test.py', (err, stream) => {
    if (err) throw err;
    stream.on('close', (code, signal) => {
      console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
      conn.end();
    }).on('data', (data) => {
      console.log('STDOUT: ' + data); //I want this data outside of the whole scope
    }).stderr.on('data', (data) => {
      console.log('STDERR: ' + data);
    });
  });
}).connect({
  host: 'x.x.x.x',
  port: 22,
  username: 'abc',
  privateKey: readFileSync('./id_rsa')
});

in outside if I do console.log(data) it did not print out anything

I am new in node js how can I get the execution result STDOUT : data of python test.py to outside of the method

Any help would be appreciable

Rajarshi Das
  • 11,778
  • 6
  • 46
  • 74

1 Answers1

1

One way would be to wrap the code in a promise:

function execScript() {
  return new Promise((resolve, reject) => {
    conn.on('ready', () => {     
      console.log('Client :: ready');
      console.log("We will execute the file " + filename);
      conn.exec('python ~/test.py', (err, stream) => {
        if (err) throw err;
        stream.on('close', (code, signal) => {
          console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
          conn.end();
        }).on('data', (data) => {
          console.log('STDOUT: ' + data); //I want this data outside of the whole scope
          resolve(data.toString());
        }).stderr.on('data', (data) => {
          console.log('STDERR: ' + data);
        });
      });
    }).connect({
      host: 'x.x.x.x',
      port: 22,
      username: 'abc',
      privateKey: readFileSync('./id_rsa')
    });
  });
}

(async () => {
  const scriptStdout = await execScript();
  console.log(scriptStdout); // This should be STDOUT
})();
Alan Friedman
  • 1,582
  • 9
  • 7