I'm trying to figure out the best and fastest way to tell if a file exists on an ftp server.
This is what I came up with...
def remote_exists?(idx)
#@file.rewind if @file.eof?
ftp = Net::FTP.new(FTP_SERVER)
ftp.login
begin
ftp.size(idx)
rescue Exception
return false
end
true
end
It seems like just capturing every exception is a bad idea but I had trouble getting the correct specific exception(s).
I'm also using OpenURI in my code to actually get the file. I was trying to figure out if that might have some method that might be better but I think it just uses Net::FTP anyway.
I think your approach seems fine except for one thing: not all FTP servers support the SIZE
command, it was introduced in the Extensions of FTP, so there's no guarantee. Your exception handling is also a bit coarse, as you noticed yourself. I would suggest to rescue FTPReplyError
specifically. In case it gives you an indication that SIZE is not implemented (500 or 502) you should probably rely on a fallback, more on that after the updated code:
def remote_exists?(idx)
ftp = Net::FTP.new(FTP_SERVER)
ftp.login
begin
ftp.size(idx)
rescue FTPReplyError => e
reply = e.message
err_code = reply[0,3].to_i
unless err_code == 500 || err_code == 502
# other problem, raise
raise
end
# fallback solution
end
true
end
A viable fallback would be to retrieve the list of files with FTP#list
, then iterate through them and compare with idx
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With