poxion
poxion

Reputation: 872

Hapi.response.File on reply completion

I'm using hapi.js as my api framework, and I've got a scenario where the GET path downloads a file (a temp file on the server).

On completion of the download, the server is suppose to delete the temp file.

At the moment, download of the file is done using 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);

Is there a simple way to inject an 'on end' event function?

Upvotes: 3

Views: 3401

Answers (1)

rlay3
rlay3

Reputation: 10562

Not sure if it is considered simple, but you can hook into Hapi's onPreResponse server event, and from there listen for the finish response event. According to the Hapi documentation the finish event is

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

So should be safe to remove the temporary file on that event.

Something like this should do the trick (based on 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);
});

Also, there is neater way of serving a file:

reply.file(path, [options])

Check out the docs here

Upvotes: 5

Related Questions