diff --git a/src/server.js b/src/server.js index 0c0081d..6054621 100644 --- a/src/server.js +++ b/src/server.js @@ -336,6 +336,17 @@ app.get('/*', asyncHandler(async (req, res, next) => { } const varyAcceptEncoding = fileEncodings.length > 0; + const sendFileHeaders = () => { + stats.handleServedFile(pathName); + res.setHeader('Content-Type', fileType.type); + if (contentEncoding !== null) { + res.setHeader('Content-Encoding', contentEncoding); + } + if (varyAcceptEncoding) { + res.setHeader('Vary', 'Accept-Encoding'); + } + }; + if (requiresSpecialRewriting) { let fileContents = await readFile(filePath, 'utf-8'); @@ -376,23 +387,25 @@ app.get('/*', asyncHandler(async (req, res, next) => { fileContents = fileContents.replace('', newHead + ''); } - res.setHeader('Content-Type', fileType.type); - if (varyAcceptEncoding) { - res.setHeader('Vary', 'Accept-Encoding'); - } + sendFileHeaders(); res.send(fileContents); } else { - const headers = {}; - headers['Content-Type'] = fileType.type; - if (contentEncoding !== null) { - headers['Content-Encoding'] = contentEncoding; - } - if (varyAcceptEncoding) { - headers['Vary'] = 'Accept-Encoding'; - } - - res.sendFile(filePath, { - headers + const readStream = fs.createReadStream(filePath, { + highWaterMark: 1024 * 64 + }); + readStream.on('open', () => { + sendFileHeaders(); + res.setHeader('Content-Length', fileStat.size); + readStream.pipe(res); + res.on('close', () => { + readStream.destroy(); + }); + res.on('error', (err) => { + readStream.destroy(err); + }); + }); + readStream.on('error', (err) => { + next(err); }); } }));