Reputation: 160
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 :
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.
Upvotes: 2
Views: 2848
Reputation: 36339
Listen to the error
event:
conn.on('error', function(e) { /* do whatever */ });
Right now, your process crashes b/c that connection error is unhandled.
Upvotes: 6