From 66603815971fc7a7606906bc3ffc6bf9508daf0f Mon Sep 17 00:00:00 2001 From: Amit Portnoy Date: Tue, 14 Feb 2017 11:10:39 +0200 Subject: [PATCH] don't read to file when the browser cache is valid --- index.js | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index abd883c..01db2c7 100644 --- a/index.js +++ b/index.js @@ -116,13 +116,19 @@ function send(ctx, path, opts) { } if (setHeaders) setHeaders(ctx.res, path, stats); - - // stream - ctx.set('Content-Length', stats.size); + if (!ctx.response.get('Last-Modified')) ctx.set('Last-Modified', stats.mtime.toUTCString()); if (!ctx.response.get('Cache-Control')) ctx.set('Cache-Control', 'max-age=' + (maxage / 1000 | 0)); - ctx.type = type(path); - ctx.body = fs.createReadStream(path); + if (ctx.fresh) { + // the browser has a valid cache for this file + ctx.status = 304; + ctx.body = null; + } else { + // stream + ctx.set('Content-Length', stats.size); + ctx.type = type(path); + ctx.body = fs.createReadStream(path); + } return path; });