Skip to content

Commit b32b8a4

Browse files
committed
Add encoding sniffing
1 parent 1e89681 commit b32b8a4

File tree

3 files changed

+457
-21
lines changed

3 files changed

+457
-21
lines changed

lib/core/index.js

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ const version = require('../../package.json').version;
1212
const status = require('./status-handlers');
1313
const generateEtag = require('./etag');
1414
const optsParser = require('./opts');
15+
const htmlEncodingSniffer = require('html-encoding-sniffer');
16+
const { Readable } = require('stream');
1517

1618
let httpServerCore = null;
1719

@@ -234,8 +236,12 @@ module.exports = function createMiddleware(_dir, _options) {
234236
let cacheControl = cache;
235237
let stream = null;
236238
if (contentType && isTextFile(contentType)) {
237-
// Assume text types are utf8
238-
contentType += '; charset=UTF-8';
239+
const htmlBytes = fs.readFileSync(file);
240+
const sniffedEncoding = htmlEncodingSniffer(htmlBytes, {
241+
defaultEncoding: 'UTF-8'
242+
});
243+
contentType += `; charset=${sniffedEncoding}`;
244+
stream = Readable.from(htmlBytes)
239245
}
240246

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

320-
stream = fs.createReadStream(file);
326+
// stream may already have been assigned during encoding sniffing.
327+
if (stream === null) {
328+
stream = fs.createReadStream(file);
329+
}
321330

322331
stream.pipe(res);
323332
stream.on('error', (err) => {

0 commit comments

Comments
 (0)