UNPKG

als-send-file

Version:

file serving with advanced options for caching, headers, and error handling, compatible with Express middleware.

35 lines (29 loc) 1.24 kB
/** * Generates an ETag and handles If-None-Match and If-Modified-Since headers. * @param {http.IncomingMessage} req - The request object. * @param {http.ServerResponse} res - The response object. * @param {Object} stats - The file stats object. * @returns {boolean} - Returns true if the response was not modified, otherwise false. */ function generateETag(req, res, stats) { let { mtimeMs, mtime, ino } = stats const etag = ino.toString() + mtimeMs.toString(); res.setHeader('Last-Modified', mtime.toUTCString()); res.setHeader('ETag', etag); const clientEtag = req.headers['if-none-match']; const clientLastModified = req.headers['if-modified-since']; if (!clientEtag && !clientLastModified) return false; const lastModifiedTime = new Date(clientLastModified).getTime() let notModified = false if(!isNaN(lastModifiedTime)) { const roundedTimeMs = new Date(Math.floor(mtimeMs / 1000) * 1000); // round Last Three Digits To Zero notModified = lastModifiedTime >= roundedTimeMs } if (clientEtag === etag || notModified) { res.statusCode = 304; res.end(); return true; } return false; } module.exports = generateETag;