diff --git a/lib/buffer.js b/lib/buffer.js index a68718848c1a49..05b57275f03dca 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -782,13 +782,22 @@ function byteLength(string, encoding) { if (len === 0) return 0; - if (encoding) { - const ops = getEncodingOps(encoding); - if (ops) { - return ops.byteLength(string); - } + if (!encoding || encoding === 'utf8') { + return byteLengthUtf8(string); + } + + if (encoding === 'ascii') { + return len; } - return byteLengthUtf8(string); + + const ops = getEncodingOps(encoding); + if (ops === undefined) { + // TODO (ronag): Makes more sense to throw here. + // throw new ERR_UNKNOWN_ENCODING(encoding); + return byteLengthUtf8(string); + } + + return ops.byteLength(string); } Buffer.byteLength = byteLength;