Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

nodejs : event listerner code make it asyn await to get promise response back

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any help would be appreciable

>Solution :

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
})();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading