theophilusx / ssh2-sftp-client

a client for SSH2 SFTP
Apache License 2.0
808 stars 199 forks source link

Cant get filter function to work with downloadDir method #514

Closed Hedronmx closed 8 months ago

Hedronmx commented 8 months ago

await sftp .downloadDir(sftp_historical, sftp_destination, { useFastget: true, filter: function test(filePath, isDirectory) { console.log(isDirectory) }, }) .then((data) => { console.log(" Files Downloaded OK!"); return data; }) .catch((err) => { console.error(err, "catch error"); });

This is my code, I cant make the filter function work. I just want to filter directory from being downloaded. I get the following error

< Error: downloadDir: filter is not a function

theophilusx commented 8 months ago

I suspect your error is because your filter function does not return a value. The filter function must return either a true or false value, depending on whether the item should be kept or dropped. Functions return the result of the last statement if no explicit return is provided. As you are calling console.log(), the return value is 'undefined' because that is what console.log returns.

Also, you should not mix async/await and promise chains - use one or the other.

For example (untested off the top of my head!) to filter out directories, so only files are downloaded from the src directory...

try { const result = await sftp.downloadDir(srcDir, dstDir, { filter: (filePath, isDir) => { return !isDir; } }) console.log('Directory downloaded') } catch (err) { console.log(Error downloading directory: ${err.message}); }

or using a promise chain

sftp.downloadDir(src, dst, { filter: (filePath, isDir) => { return !isDir }

}).then(resp => { console.log('Directoryh downlaoded'); }).catch(err => { console.log(Error downloading dir: ${err.message}); })

More examples can be found in the test directory of the repo.

Also note, best to get it working with get() and then when you know it is working, try enabling fastGet. Reason is that fastGet is very dependent on non-standardised fucntionality in the remote sftp server. Not all sftp servers will support it, so best to get things working with plain get (the default) and once you know it works, enable fastGet.

Finally, be advised there is a known bug in downloadDir for very large directories. This bug has been fixed in the current master branch, but has not yet been pushed out as version 10.0.0. This should occur in the next day or so.

Hedronmx commented 8 months ago

Hey! I figured out why it wasn't working. I just had to update the package! Thank you so much for your quick and asserted response.