Created
August 23, 2013 11:00
-
-
Save wjlroe/6318044 to your computer and use it in GitHub Desktop.
How to stream a file download with em-http
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'em-http' | |
require 'eventmachine' | |
url = ARGV[0] | |
puts "going to try to download #{url}" | |
EventMachine.run do | |
req = EventMachine::HttpRequest.new(url).get | |
File.unlink("really_big_file") if File.exist?("really_big_file") | |
req.headers do |headers| | |
if headers.status != 200 | |
puts "Failed to download! Status: #{headers.status}" | |
req.close | |
EM.stop | |
end | |
end | |
req.stream do |chunk| | |
File.open("really_big_file", 'a') do |fd| | |
fd.write(chunk) | |
end | |
end | |
req.callback do | |
puts "File downloaded successfully it seems" | |
EM.stop | |
end | |
req.errback do | |
req.close | |
puts "Argh! Error downloading the thing" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment