简体   繁体   中英

make node.js not exit after ssh2 connection error

I have the following code in my node.js app to test the SSH connection to a server using ssh2 :

    var Connection   = require('ssh2');
    var conn         = new Connection();
    conn.on('ready', function() {
        console.log('Connection :: ready');
        conn.exec('uptime', function(err, stream) {
            if (err) throw err;
            stream.on('exit', function(code, signal) {
              console.log('Stream :: exit :: code: ' + code + ', signal: ' + signal);
            }).on('close', function() {
              console.log('Stream :: close');
              conn.end();
            }).on('data', function(data) {
              console.log('STDOUT: ' + data);
            }).stderr.on('data', function(data) {
              console.log('STDERR: ' + data);
            });
        });
    }).connect({
      host: serverIp,
      port: serverPort,
      username: serverUsername,
      privateKey: require('fs').readFileSync('./id_rsa')
    });

It works fine, but if it returns an error, if I get a connection timeout for example, the node.js app crashes...

I would like to do the following :

  • if an error is returned, simply redirect to /servers page without crashing the app.

I tried to change the "if (err) throw err;" line with "if (err) res.redirect('/servers');" but it doesn't work...

Can someone help me with this noobie question ? I'm new to node.js :)

thanks a lot.

Listen to the error event:

conn.on('error', function(e) { /* do whatever */ });

Right now, your process crashes b/c that connection error is unhandled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM