问题描述:

I'm trying to retreive content of variable stdout from outside of ssh-client block in my code:

var SSH = require('simple-ssh');

var ssh = new SSH({

host: 'localhost',

user: 'username',

pass: 'password'

});

ssh.exec('echo $PATH', {

out: function(stdout) {

console.log(stdout);

}

}).start();

I need this variable's data, because in another part of code I need to parse it with another function (which deletes \n and removes '|' as delimiters with method "split") and write this information into Oracle database with oracledb-module.

Also I tried to associate ssh.exec with variable, like this:

var retreiveData = function ssh.exec('echo $PATH', {

out: function(stdout) {

console.log(stdout); // I tried to change it to "return stdout;"

}

}).start();

console.log(retrieveData());

But this didn't worked for me.

Please, help me.

网友答案:

It is a callback pattern with async nature. So in order to persist the data represented by stdout returned in the out callback function handler, you need to do something along the line of

var SSH = require('simple-ssh');

function echo(callback) {
  var ssh = new SSH({
    host: 'localhost',
    user: 'username',
    pass: 'password'
  });

  var data = '';
  var error = null;

  ssh.exec('echo $PATH', {
    out: function(stdout) {
      data += stdout;
    },
    exit: function(code) {
      if (code != 0) return callback(new Error('exit code: ' + code));

      // here's all the data you have persisted from stdout
      return callback(error, data);
    },
    error: function(err) {
      error = err;
    }
  }).start();
}

echo(function(err, data) {
  if (err) {
    // handle potential err
    console.error(err.stack);
  } else {
    // work with data as intended
    console.log(data);
  }
});
相关阅读:
Top