Skip to content

readStream decodes each chunk separately — multibyte UTF-8 characters split across chunks become U+FFFD #183

Done

Description

@maximkozlovskiy

readStream in src/main.ts builds the output with output += chunk.toString(). When a multibyte UTF-8 character (Cyrillic, CJK, emoji…) is split across two stdout chunks, each half is decoded on its own and the character turns into U+FFFD. The same command can therefore return different strings from run to run.

Impact: lint-staged (17.6, tinyexec 1.3.1) runs the same git diff --patch --raw -z before and after the tasks, and runs git add on every file whose diff text changed. With a large unstaged file containing non-ASCII text, the corrupted characters make the two diffs differ. lint-staged then stages that file, and an unrelated unstaged file lands in the commit.

Repro: a repo with an unstaged change to a ~56 KB Cyrillic markdown file (374+/93−). We ran exec('git', ['diff', '--binary', '--unified=0', '--no-color', '--patch', '--raw', '-z', …]) 30 times and compared each result with execFileSync(…, { encoding: 'utf8' }):

  • tinyexec 1.3.1: 21–24 of 30 results differ from the reference (2–4 U+FFFD each);
  • the same with the fix below: 0 of 30 differ.

Possible fix:

import {StringDecoder} from 'node:string_decoder';

async function readStream(stream: Readable): Promise<string> {
  let output = '';
  const decoder = new StringDecoder('utf8');
  try {
    for await (const chunk of stream) {
      output += typeof chunk === 'string' ? chunk : decoder.write(chunk);
    }
    output += decoder.end();
  } catch {
    // suppress errors, child process probably failed to spawn
  }
  return output;
}

(or stream.setEncoding('utf8') before iterating). The async iterator path is fine, because readline already decodes correctly.

Environment: Windows 11, Node v24.14.1, git 2.54.0.windows.1.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions