Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add encoding charset sniffing #736

Merged
merged 3 commits into from Oct 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 18 additions & 3 deletions lib/core/index.js
Expand Up @@ -5,13 +5,16 @@
const path = require('path');
const fs = require('fs');
const url = require('url');
const { Readable } = require('stream');
const buffer = require('buffer');
const mime = require('mime');
const urlJoin = require('url-join');
const showDir = require('./show-dir');
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');

let httpServerCore = null;

Expand Down Expand Up @@ -234,8 +237,17 @@ 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';
if (stat.size < buffer.constants.MAX_LENGTH) {
const bytes = fs.readFileSync(file);
const sniffedEncoding = htmlEncodingSniffer(bytes, {
defaultEncoding: 'UTF-8'
});
contentType += `; charset=${sniffedEncoding}`;
stream = Readable.from(bytes)
} else {
// Assume text types are utf8
contentType += '; charset=UTF-8';
}
}

if (file === gzippedFile) { // is .gz picked up
Expand Down Expand Up @@ -317,7 +329,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