@@ -12,6 +12,8 @@ const version = require('../../package.json').version;
12
12
const status = require ( './status-handlers' ) ;
13
13
const generateEtag = require ( './etag' ) ;
14
14
const optsParser = require ( './opts' ) ;
15
+ const htmlEncodingSniffer = require ( 'html-encoding-sniffer' ) ;
16
+ const { Readable } = require ( 'stream' ) ;
15
17
16
18
let httpServerCore = null ;
17
19
@@ -234,8 +236,12 @@ module.exports = function createMiddleware(_dir, _options) {
234
236
let cacheControl = cache ;
235
237
let stream = null ;
236
238
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 )
239
245
}
240
246
241
247
if ( file === gzippedFile ) { // is .gz picked up
@@ -317,7 +323,10 @@ module.exports = function createMiddleware(_dir, _options) {
317
323
return ;
318
324
}
319
325
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
+ }
321
330
322
331
stream . pipe ( res ) ;
323
332
stream . on ( 'error' , ( err ) => {
0 commit comments