Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
What can cause string length to be incorrectly reported in Node JavaScript?

On inspection in the debugger, the value of html in the code below ends with </html>\n as expected, but as received in browser the last six characters (/html>) are missing.

let html = this.code!.asHtml();
response.writeHead(200, {
    "Content-Type": "text/html; charset=utf-8",
    "Content-Length": html.length
});
response.end(html);

When I comment out the content length header like so

let html = this.code!.asHtml();
response.writeHead(200, {
    "Content-Type": "text/html; charset=utf-8",
    //"Content-Length": html.length
});
response.end(html);

The delivered page is no longer truncated. WTF?! This implies that html.length is not reporting the correct number of characters. Probably this has something to do with character sets, but I'm not sure how to proceed and would appreciate advice.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Content-Length is the number of bytes of the body not the number of chars.

html.length is not reporting the correct number of characters.

.length is reporting the number of characters (if it is UTF-8) or more precisely UTF-16 code units.

The length property of a String object contains the length of the string, in UTF-16 code units. length is a read-only data property of string instances. ...

Not relevant for you case but also important to know:

... it's possible for the value returned by length to not match the actual number of characters in the string

Back to your problem: In UTF-8 or 16 one character may be encoded by more than one byte. So html.length can indeed be too small. Use Buffer.byteLength(html, 'utf8') instead.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda