Skip to content
Tutorials Center
My learning

Topics

Node.js Reference · Buffers and Encoding

Node.js buffer.isUtf8() and buffer.isAscii() functions

Reference for Node.js buffer.isUtf8() and buffer.isAscii(): check whether bytes are valid UTF-8 or 7-bit ASCII before decoding, with edge cases and alternatives.

isUtf8(input) and isAscii(input) from node:buffer return true when the given bytes are valid UTF-8 text, or contain only 7-bit ASCII (byte values 0 to 127). They check the bytes without creating a string, so they are quick and use no extra memory, which makes them a good gate in front of buf.toString().

isAscii() is the stricter test: every ASCII text is also valid UTF-8, but text with accents, symbols or emoji is UTF-8 and not ASCII.

NODE
import { isUtf8, isAscii } from "node:buffer";

isUtf8(Buffer.from("héllo")); // true
isAscii(Buffer.from("héllo")); // false

Try it

Node.js Validating bytes

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Subtle cases

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
import { isUtf8, isAscii } from "node:buffer";

isUtf8(input)   // returns boolean
isAscii(input)  // returns boolean
Name Description
input A Buffer, ArrayBuffer or typed array (including Uint8Array) whose bytes are checked.

Returns: true or false.

Errors and edge cases:

  • A string or other type throws ERR_INVALID_ARG_TYPE.
  • An empty input is both valid UTF-8 and ASCII, so both functions return true.

Usage notes

  • What counts as valid UTF-8: the shortest form of each character only, no surrogate code points (U+D800 to U+DFFF), nothing above U+10FFFF, and no truncated sequences. A byte order mark is valid.
  • A chunk of a stream may fail the test simply because a character was cut at the chunk edge. Test whole messages, or use StringDecoder, which waits for the rest of a character.
  • Alternative: new TextDecoder("utf-8", { fatal: true }) throws on invalid input and also returns the decoded string, so you validate and decode in one pass. isUtf8() is better when you only need a yes or no.
  • Useful for: deciding whether file contents are text or binary, rejecting bad request bodies and choosing between toString() and a binary code path. It is not proof of a language or file type.
  • isAscii() as a fast path: if it returns true, string length equals byte length and latin1 and utf8 decode alike.
  • Cost is linear in the input size, with fast native code that is faster than decoding.
  • Added in: Node.js 18.15 and 19.4.