Skip to content

Replacements for is-utf8 ​

Both Node.js and the web platform can check for valid UTF-8 without a dependency. The two options below return the same answer, so it is only a question of where the code runs.

One difference to keep in mind: among control characters is-utf8 accepts only tab, line feed and carriage return, and rejects the other thirty even though all of them are valid UTF-8. If you were relying on that to tell text from binary, keep the check explicit.

buffer.isUtf8 (native, since Node.js v19.4.0 / v18.14.0) ​

buffer.isUtf8 takes a Buffer, TypedArray or ArrayBuffer.

ts
import isUtf8 from 'is-utf8'
import { isUtf8 } from 'node:buffer'

isUtf8(bytes)

TextDecoder (native, browsers and Node.js) ​

Elsewhere, decode with TextDecoder and fatal: true, which throws on malformed input instead of substituting replacement characters.

ts
import isUtf8 from 'is-utf8'
const decoder = new TextDecoder('utf-8', {fatal: true}) 
const isUtf8 = (bytes) => { 
  try { 
    decoder.decode(bytes) 
    return true
  } catch { 
    return false
  } 
} 

Released under the MIT License. (cb509db0)