2014-01-17 24 views
3

我使用hapi.js作爲我的api框架,並且我有一個GET路徑下載文件(服務器上的臨時文件)的場景。Hapi.response.File回覆完成

完成下載後,服務器會假設刪除臨時文件。

目前,該文件的下載使用Hapi.response.File

var response = new Hapi.response.File(path); 
req.reply(response).header('Content-disposition', 'attachment; filename=' + doc[0].file.name).header('Content-type', mimetype); 

有沒有一種簡單的方法來注入一個「的結束」事件的功能呢?

回答

5

不知道它是否被認爲是簡單的,但您可以掛接到Hapi的onPreResponse服務器事件,並從那裏監聽finish響應事件。按照哈啤文檔finish事件是

發射時的響應寫完,但客戶端 響應連接結束之前。

所以應該是安全的刪除該事件的臨時文件。 (基於哈皮V6.0.x中)

像這樣的東西應該做的伎倆:

server.ext('onPreResponse', function (request, reply) { 
    // other code here, e.g. boom checking 

    if (...) { // Test to see if the request was to download tmp file 
     request.response.once('finish', function() { 
      // delete tmp file here 
     }); 
    } 

    reply(request.response); 
}); 

此外,還有服務文件的更合適的方法:

reply.file(path, [options]) 

時退房docs here