Skip to content

Commit

Permalink
use res.sendFile instead of our custom thing
Browse files Browse the repository at this point in the history
  • Loading branch information
GarboMuffin committed Aug 19, 2024
1 parent 92d2c5b commit c003ec7
Showing 1 changed file with 15 additions and 37 deletions.
52 changes: 15 additions & 37 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -336,17 +336,6 @@ 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');

Expand Down Expand Up @@ -387,34 +376,23 @@ app.get('/*', asyncHandler(async (req, res, next) => {
fileContents = fileContents.replace('</head>', newHead + '</head>');
}

sendFileHeaders();
res.setHeader('Content-Type', fileType.type);
if (varyAcceptEncoding) {
res.setHeader('Vary', 'Accept-Encoding');
}
res.send(fileContents);
} else {
const stream = fs.createReadStream(filePath);

// If the stream is taking a completely unreasonable amount of time, assume that something timed
// out and the connection ought to be killed.
const timeoutId = setTimeout(() => {
// Will trigger stream error handler.
stream.destroy(new Error('Timed out'));
}, 1000 * 60 * 60);

const onResponseClose = () => {
logger.warn('Response closed');
};
res.on('close', onResponseClose);

stream.on('open', () => {
sendFileHeaders();
res.setHeader('Content-Length', fileStat.size);
stream.pipe(res);
});
stream.on('end', () => {
clearTimeout(timeoutId);
res.off('close', onResponseClose);
});
stream.on('error', (err) => {
next(err);
const headers = {};
headers['Content-Type'] = fileType.type;
if (contentEncoding !== null) {
headers['Content-Encoding'] = contentEncoding;
}
if (varyAcceptEncoding) {
headers['Vary'] = 'Accept-Encoding';
}

res.sendFile(filePath, {
headers
});
}
}));
Expand Down

0 comments on commit c003ec7

Please sign in to comment.