return value from a function node js ssh2

how to return the values (data) of the getData function bellow?

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

const conn = new Client();

function getData() {
    //i tried to assign the data to a variable but failed
    //var rawData = '';

    conn.on('ready', () => {
        conn.exec('pwd', (err,stream)=>{
            if (err) throw err;
            stream.on('data',(data)=>{
                //the console successfully displayed - the current path
                console.log('Output:' + data);
                //if i return the data here the output was undefined
                //return data
            });
            stream.stderr.on('data',(data)=>{
               
            });
            stream.on('close',(code,signal)=>{
                conn.end();
            });
            //if i tried to get the data values here, it threw "unhandled 'error' event", so i would not possible to return the data here.
            //console.log(data);
            
        });
    }).connect({
        host: 'myserver',
        port: 22,
        username: 'root',
        password: 'roots!'
    });
}


getData();

consoling out from inside stream is success, but how to return the data?
i tried to assign the data to variable (rawaData), but confusing where to put the ‘return’ code.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use a promise to communicate back the final result:

function getData() {
    return new Promise((resolve, reject) => {
        let allData = "";
        conn.on('ready', () => {
            conn.exec('pwd', (err, stream) => {
                if (err) {
                    reject(err);
                    conn.end();
                    return;
                }
                stream.on('data', (data) => {
                    allData += data;
                });
                stream.on('close', (code, signal) => {
                    resolve(allData);
                    conn.end();
                });
                stream.on('error', reject);
            });
        }).connect({
            host: 'myserver',
            port: 22,
            username: 'root',
            password: 'roots!'
        });
    });
}


getData().then(result => {
    console.log(result);
}).catch(err => {
    console.log(err);
});;


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x