添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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.

i have read about promise but i didn't know how to implement it on my script. but i solved know. thank you for your response – aldiano_febrian Mar 6, 2022 at 7:34

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);
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.