Skip to content

Commit

Permalink
Add encoding sniffing
Browse files Browse the repository at this point in the history
  • Loading branch information
boarwell committed Oct 19, 2021
1 parent 1e89681 commit b32b8a4
Show file tree
Hide file tree
Showing 3 changed files with 457 additions and 21 deletions.
15 changes: 12 additions & 3 deletions lib/core/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ const version = require('../../package.json').version;
const status = require('./status-handlers');
const generateEtag = require('./etag');
const optsParser = require('./opts');
const htmlEncodingSniffer = require('html-encoding-sniffer');
const { Readable } = require('stream');

let httpServerCore = null;

Expand Down Expand Up @@ -234,8 +236,12 @@ module.exports = function createMiddleware(_dir, _options) {
let cacheControl = cache;
let stream = null;
if (contentType && isTextFile(contentType)) {
// Assume text types are utf8
contentType += '; charset=UTF-8';
const htmlBytes = fs.readFileSync(file);
const sniffedEncoding = htmlEncodingSniffer(htmlBytes, {
defaultEncoding: 'UTF-8'
});
contentType += `; charset=${sniffedEncoding}`;
stream = Readable.from(htmlBytes)
}

if (file === gzippedFile) { // is .gz picked up
Expand Down Expand Up @@ -317,7 +323,10 @@ module.exports = function createMiddleware(_dir, _options) {
return;
}

stream = fs.createReadStream(file);
// stream may already have been assigned during encoding sniffing.
if (stream === null) {
stream = fs.createReadStream(file);
}

stream.pipe(res);
stream.on('error', (err) => {
Expand Down
Loading

0 comments on commit b32b8a4

Please sign in to comment.