From c2bd6c0409e1644d63630c747b72bec8173b187c Mon Sep 17 00:00:00 2001 From: giancarloscolaro <36232485+giancarloscolaro@users.noreply.github.com> Date: Thu, 22 Feb 2018 10:46:33 -0300 Subject: [PATCH] Protect download of inexistent files Protecting the download function when the remote file doesn't exist. This prevents file descriptor leak and creating a empty local file. --- lib/client.js | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/lib/client.js b/lib/client.js index 4af629d..58ba422 100644 --- a/lib/client.js +++ b/lib/client.js @@ -291,19 +291,24 @@ Client.prototype.download = function(src, dest, callback) { if (err) { return callback(err); } - - var sftp_readStream = sftp.createReadStream(src); - sftp_readStream.on('error', function(err){ - callback(err); - }); - sftp_readStream.pipe(fs.createWriteStream(dest)) - .on('close',function(){ - self.emit('read', src); - self.close(); - callback(null); - }) - .on('error', function(err){ - callback(err); + sftp.stat(src, function(err, attr) { + if (err) { + return callback(err); + } else { + var sftp_readStream = sftp.createReadStream(src); + sftp_readStream.on('error', function(err){ + callback(err); + }); + sftp_readStream.pipe(fs.createWriteStream(dest)) + .on('close',function(){ + self.emit('read', src); + self.close(); + callback(null); + }) + .on('error', function(err){ + callback(err); + }); + } }); }); };