diff --git a/src/main.ts b/src/main.ts index 424d1e7..03795d6 100644 --- a/src/main.ts +++ b/src/main.ts @@ -8,7 +8,7 @@ import { import {type Readable} from 'node:stream'; import {cwd as getCwd} from 'node:process'; import {computeEnv} from './env.js'; -import {combineStreams} from './stream.js'; +import {combineStreams, readStream} from './stream.js'; import readline from 'node:readline'; import {normalizeSpawnCommand} from './normalize.js'; import {NonZeroExitError} from './non-zero-exit-error.js'; @@ -111,20 +111,6 @@ function combineSignals(signals: Iterable): AbortSignal { return controller.signal; } -async function readStream(stream: Readable): Promise { - let output = ''; - - try { - for await (const chunk of stream) { - output += chunk.toString(); - } - } catch { - // suppress errors, child process probably failed to spawn - } - - return output; -} - export class ExecProcess implements Result { protected _process?: ChildProcess; protected _aborted: boolean = false; diff --git a/src/stream.ts b/src/stream.ts index 6750b09..7476af0 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -1,6 +1,7 @@ import {type EventEmitter} from 'node:events'; import {pipeline} from 'node:stream/promises'; import {type Readable, PassThrough} from 'node:stream'; +import {StringDecoder} from 'node:string_decoder'; export const waitForEvent = ( emitter: EventEmitter, @@ -28,3 +29,19 @@ export const combineStreams = (streams: Readable[]): Readable => { return combined; }; + +export async function readStream(stream: Readable): Promise { + let output = ''; + const decoder = new StringDecoder(); + + 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; +} diff --git a/src/test/stream_test.ts b/src/test/stream_test.ts index 79f9c7d..8d8c9e8 100644 --- a/src/test/stream_test.ts +++ b/src/test/stream_test.ts @@ -1,4 +1,4 @@ -import {combineStreams, waitForEvent} from '../stream.js'; +import {combineStreams, readStream, waitForEvent} from '../stream.js'; import {describe, test, expect} from 'vitest'; import {EventEmitter} from 'node:events'; import {Readable} from 'node:stream'; @@ -70,3 +70,13 @@ describe('combineStreams', async () => { expect(chunks).toEqual(['foo', 'bar']); // no time for 'baz' before stream0 was destroyed }); }); + +describe('readStream', async () => { + test('decodes multibyte characters split across chunks', async () => { + const stream = Readable.from([ + Buffer.from([0xf0, 0x9f]), + Buffer.from([0x9a, 0x80]) + ]); + expect(await readStream(stream)).toBe('🚀'); + }); +});