NodeJS - Check whether a SFTP remote file exists using "Sequest"

I'm new to NodeJS and I'm using "Sequest" package for reading contents of a SFTP remote file. It works great. However if the file that I'm trying to read, does not exist, then it throws exception and the app does not respond further.

So I want to check whether the file exists before trying to read it. Since I'm using a library function (sequest.get), I'm unable to handle the exception that occurs in the library method due to absence of the file specified.

Below is my code:

var reader = sequest.get('xyz@abc', fileName, opts);
    reader.setEncoding('utf8');
    reader.on('data', function(chunk) {
                        return res.send(chunk);
    });

reader.on('end', function() {
    console.log('there will be no more data.');
});

Ref: https://github.com/mikeal/sequest#gethost-path-opts

Sequest (https://github.com/mikeal/sequest) is a wrapper to SSH2 - (https://github.com/mscdex/ssh2).

Any help is greatly appreciated. Thank you.

Upvotes: 1

Views: 1580

Answers (1)

vinayr
vinayr

Reputation: 11234

You can listen to error event to handle such cases.

var reader = sequest.get('xyz@abc', fileName, opts);

reader.setEncoding('utf8');

reader.on('data', function(chunk) {
  return res.send(chunk);
});

reader.on('end', function() {
  console.log('there will be no more data.');
});

reader.on('error', function() {
  console.log('file not found or some other error');
});

Upvotes: 1

Related Questions