2012-11-21 64 views
2

我試圖打開一個img文件並通過http發送它。我已經讀過,最好的方法是creatReadStream,因爲它是異步的,性能更好。createReadStream發送文件http

這是我的代碼:

var file = fs.createReadStream(image); 

    file.on("error", function(err){ 
     ... 
    }); 

    res.writeHead(200, {"Content-Type" : "image/png"}); 

    file.on("data", function(data) { 
     res.write(data); 
    }) 

    file.on("end", function() { 
     res.end(); 
    }) 

我怎樣才能知道文件的大小,讓水庫知道爲了把它的頭?

我不喜歡在回調中寫頭,我該怎麼辦?

謝謝。

回答

4
var stat = fs.statSync('path/to/imagefile'); 
response.writeHead(200, { 
    'Content-Type' : 'image/png', 
    'Content-Length': stat.size 
}); 
fs.createReadStream('path/to/imagefile').pipe(response); 
+1

我回復了你作爲自己的答案,因爲代碼。 – Mario

3

res.writeHead()調用位置正確,但事件偵聽器可以替換爲file.pipe(res);,因爲您只是將數據從讀取流轉發到res的寫入數據流。此外,HTTP響應代碼202似乎不適合,爲什麼不使用200

var file = fs.createReadStream(image); 
res.writeHead(200, {"Content-Type" : "image/png"}); 
file.pipe(res); 
+0

202是一個拼寫錯誤,謝謝:) – Mario

1

@wayne非常感謝你的回答,但不會是更好的異步使用統計信息?

var stat = fs.stat(image, function(err,stats) { 
     if (err) { 
      req_error(res,err); 
     } else { 
      res.writeHead(200, { 
      'Content-Type' : 'image/png', 
      'Content-Length': stats.size 
      }); 

      var file = fs.createReadStream(image); 
      file.pipe(res); 
     }; 
    }); 
+1

是的,儘可能使用異步。我沒有使用異步,因爲我在兩個回調中有這部分代碼,所以爲了簡單起見,我做了stateSync。 – wayne