gpt4 book ai didi

node.js - Hapi.response.File 回复完成

转载 作者:搜寻专家 更新时间:2023-10-31 23:38:50 26 4
gpt4 key购买 nike

我使用 hapi.js 作为我的 api 框架,我有一个场景,其中 GET 路径下载一个文件(服务器上的一个临时文件)。

下载完成后,服务器会删除临时文件。

目前,文件的下载是使用 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);

是否有一种简单的方法来注入(inject)“on end”事件函数?

最佳答案

不确定它是否被认为是简单的,但您可以连接到 Hapi 的 onPreResponse 服务器事件,并从那里监听 finish 响应事件。根据 Hapi 文档,finish 事件是

emitted when the response finished writing but before the client response connection is ended.

因此删除该事件的临时文件应该是安全的。

像这样的东西应该可以解决问题(基于 Hapi 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])

查看文档 here

关于node.js - Hapi.response.File 回复完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21177299/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com