Skip to content

Commit b0cb863

Browse files
committed
Fix encoding sniffing strategy
1 parent 5dfc780 commit b0cb863

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

lib/core/index.js

+13-7
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
const path = require('path');
66
const fs = require('fs');
77
const url = require('url');
8+
const { Readable } = require('stream');
9+
const buffer = require('buffer');
810
const mime = require('mime');
911
const urlJoin = require('url-join');
1012
const showDir = require('./show-dir');
@@ -13,7 +15,6 @@ const status = require('./status-handlers');
1315
const generateEtag = require('./etag');
1416
const optsParser = require('./opts');
1517
const htmlEncodingSniffer = require('html-encoding-sniffer');
16-
const { Readable } = require('stream');
1718

1819
let httpServerCore = null;
1920

@@ -236,12 +237,17 @@ module.exports = function createMiddleware(_dir, _options) {
236237
let cacheControl = cache;
237238
let stream = null;
238239
if (contentType && isTextFile(contentType)) {
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)
240+
if (stat.size < buffer.constants.MAX_LENGTH) {
241+
const bytes = fs.readFileSync(file);
242+
const sniffedEncoding = htmlEncodingSniffer(bytes, {
243+
defaultEncoding: 'UTF-8'
244+
});
245+
contentType += `; charset=${sniffedEncoding}`;
246+
stream = Readable.from(bytes)
247+
} else {
248+
// Assume text types are utf8
249+
contentType += '; charset=UTF-8';
250+
}
245251
}
246252

247253
if (file === gzippedFile) { // is .gz picked up

0 commit comments

Comments
 (0)