Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

284
Vistas
Check if file/blob object is valid UTF-8

I need a function that can check if a file or blob object is valid UTF-8. I can get the text and check for � characters, but if the string has that character to begin with, the function would mark it as invalid.

function isUTF8(blob) {
  return new Promise(async resolve => {
    const text = await blob.text();
    resolve(!~text.indexOf("�"));
  });
}

// "�" is valid utf-8 but the function returns false
isUTF8(new Blob(["�"])).then(console.log);

// returns true
isUTF8(new Blob(["example"])).then(console.log);

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can use the TextDecoder API:

async function isUTF8(blob) {
  const decoder = new TextDecoder('utf-8', { fatal: true });
  const buffer = await blob.arrayBuffer();
  try {
    decoder.decode(buffer);
  } catch (e) {
    if (e instanceof TypeError)
      return false;
    throw e;
  }
  return true;
}

(async () => {

console.log(await isUTF8(new Blob(
  [new Uint8Array([0x80])]))); // false
console.log(await isUTF8(new Blob(
  [new Uint8Array([0xef, 0xbf, 0xbd])]))); // true
console.log(await isUTF8(new Blob(
  ["\ufffd"]))); // true
console.log(await isUTF8(new Blob(
  ["example"]))); // true

})().catch(e => console.warn(e));

The above loads the entire Blob into an ArrayBuffer for simplicity. If memory-efficiency becomes an issue, you may look into using the .stream() method to process the Blob in parts, without holding it in memory in its entirety.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda