2

I was looking at downloading scripts in Ruby and most of them end up like this :

File.open(fileName, 'wb') do |output|
  open(@url) do |data|
    output.write(data.read)
  end
end

this approach seems to open a stream and download the file completely and FINALLY save the data to the file... Is there a way to make the code save the ALREADY DOWNLOADED data to the file periodically ?

for example out of a 100MB Youtube video, I want the script to save every 1MB it downloads to the file and continue doing this until the download is finished...

This way you could open the file with a suitable player and play it before the download is finished.

Thanks...

Cypher
  • 2,374
  • 4
  • 24
  • 36

1 Answers1

2

OpenURI seems to read the entire file before passing it to the block, but you can use Net::HTTP to stream the response body:

require 'net/http'

uri = URI(@url)

Net::HTTP.start(uri.host, uri.port) do |http|
  request = Net::HTTP::Get.new uri

  http.request request do |response|
    open file_name, 'w' do |io|
      io.sync = true
      response.read_body do |chunk|
        io.write chunk
      end
    end
  end
end

Note the IO#sync= call to set the “sync mode”.

Stefan
  • 109,145
  • 14
  • 143
  • 218
  • Thanks ! by the way, what does "io.sync" do in your code ? – Cypher Jan 30 '15 at 11:14
  • From the linked documentation: *"When sync mode is true, all output is immediately flushed to the underlying operating system and is not buffered internally."*. In other words: your files grows as the download proceeds. – Stefan Jan 30 '15 at 11:17