Skip to content

Instantly share code, notes, and snippets.

@wjlroe
Created August 23, 2013 11:00
Show Gist options
  • Save wjlroe/6318044 to your computer and use it in GitHub Desktop.
Save wjlroe/6318044 to your computer and use it in GitHub Desktop.
How to stream a file download with em-http
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