2013-10-22 48 views
0

模擬連接速度慢我是一個前端開發者,當我的代碼我使用西納特拉作爲一個靜態文件服務器後端:與西納特拉

require 'sinatra' 

configure do 
    set :public_folder, File.dirname(__FILE__) 
end 

get '/' do 
    send_file File.join(settings.public_folder, 'index.html') 
end 

get '/:name' do 
    file = File.join(settings.public_folder, params[:name]) 
    if File.exist?(file) 
    send_file file 
    else 
    halt 404 
    end 
end 

我很高興與,但是這一次我得到一個任務創建一個JS介紹,僅在頁面加載時執行一些複雜的行爲。

我無法測試此類JS行爲,因爲在我的開發沙箱中,Sinatra立即爲文件提供服務。

我如何使Sinatra緩慢地以給定的最大速率提供文件e。 G。 10 Kbps?替代方法建議也值得讚賞。

回答

3

如果拆分一個文件分割成塊,並逐漸展露他們來說,這是可能的,這裏有一個例子:

require 'sinatra' 
require "sinatra/streaming" 

def file_chunks 
    [].tap do |chunks| 
    File.open("index.html", "rb") do |io| 
     while not io.eof? 
     chunks << io.read(10) 
     end 
    end 
    end 
end 

get '/send_file_slowly' do 
    stream do |out| 
    file_chunks.each do |chunk| 
     out.print chunk 
     out.flush 
     sleep 0.2 
    end 
    end 
end 
+2

尼斯的答案,+1(想這可能是更多)。 – iain