Add `binary` and `preserveNewlines` options to `subprocess.readable()` (#922)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent bedb729 · Browse files · 15 files·+375 added−88 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+375 added−88 removed
- tests:+166 added−18 removed
- other:+209 added−70 removed
Provenance
- Commit
56ee48e- Tree
8762c49- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
bedb729
15 files changed+375 added−88 removed
modified:lib/convert/concurrent.js+2 added-8 removed
12345614 unmodified lines212223242324252627282930252627285 unmodified linesimport {createDeferred} from './shared.js';
// When using multiple `.readable()`/`.writable()`/`.duplex()`, `final` and `destroy` should wait for other streamsexport const initializeConcurrentStreams = () => ({ readableDestroy: new WeakMap(), writableFinal: new WeakMap(),14 unmodified lines const resolve = promise.resolve.bind(promise); return {resolve, promises};};
const createDeferred = () => { let resolve; const promise = new Promise(resolve_ => { resolve = resolve_; }); return Object.assign(promise, {resolve});};
// Wait for other streams, but stop waiting when subprocess endsexport const waitForConcurrentStreams = async ({resolve, promises}, subprocess) => { resolve(); const [isSubprocessExit] = await Promise.race([5 unmodified linesmodified:lib/convert/duplex.js+9 added-6 removed
1234567894 unmodified lines1415161717181920212223212425262427282629302831323033343536376 unmodified linesimport {Duplex} from 'node:stream';import {callbackify} from 'node:util';import { getSubprocessStdout, getReadableOptions, getReadableMethods, onStdoutFinished, onReadableDestroy,} from './readable.js';4 unmodified lines onWritableDestroy,} from './writable.js';
// Create a `Duplex` stream combining bothexport const createDuplex = ({subprocess, concurrentStreams}, {from, to} = {}) => {export const createDuplex = ({subprocess, concurrentStreams}, {from, to, binary = true, preserveNewlines = true} = {}) => { const {subprocessStdout, waitReadableDestroy} = getSubprocessStdout(subprocess, from, concurrentStreams); const {subprocessStdin, waitWritableFinal, waitWritableDestroy} = getSubprocessStdin(subprocess, to, concurrentStreams); const {readableEncoding, readableObjectMode, readableHighWaterMark} = getReadableOptions(subprocessStdout, binary); const {read, onStdoutDataDone} = getReadableMethods({subprocessStdout, subprocess, binary, preserveNewlines}); const duplex = new Duplex({ ...getReadableMethods(subprocessStdout, subprocess), read, ...getWritableMethods(subprocessStdin, subprocess, waitWritableFinal), destroy: callbackify(onDuplexDestroy.bind(undefined, {subprocessStdout, subprocessStdin, subprocess, waitReadableDestroy, waitWritableFinal, waitWritableDestroy})), readableHighWaterMark: subprocessStdout.readableHighWaterMark, readableHighWaterMark, writableHighWaterMark: subprocessStdin.writableHighWaterMark, readableObjectMode: subprocessStdout.readableObjectMode, readableObjectMode, writableObjectMode: subprocessStdin.writableObjectMode, encoding: subprocessStdout.readableEncoding, encoding: readableEncoding, }); onStdoutFinished(subprocessStdout, duplex, subprocess, subprocessStdin); onStdoutFinished({subprocessStdout, onStdoutDataDone, readable: duplex, subprocess, subprocessStdin}); onStdinFinished(subprocessStdin, duplex, subprocessStdout); return duplex;};
6 unmodified linesadded:lib/convert/loop.js+97 added
1+import {on} from 'node:events';2+import {getEncodingTransformGenerator} from '../stdio/encoding-transform.js';3+import {getSplitLinesGenerator} from '../stdio/split.js';4+5+export const iterateOnStdout = ({subprocessStdout, subprocess, binary, preserveNewlines}) => {6+ const controller = new AbortController();7+ stopReadingOnExit(subprocess, controller);8+ const onStdoutChunk = on(subprocessStdout, 'data', {9+ signal: controller.signal,10+ highWaterMark: HIGH_WATER_MARK,11+ // Backward compatibility with older name for this option12+ // See https://github.com/nodejs/node/pull/52080#discussion_r152522786113+ // @todo Remove after removing support for Node 2114+ highWatermark: HIGH_WATER_MARK,15+ });16+ const onStdoutData = iterateOnData({subprocessStdout, onStdoutChunk, controller, binary, preserveNewlines});17+ return onStdoutData;18+};19+20+const stopReadingOnExit = async (subprocess, controller) => {21+ try {22+ await subprocess;23+ } catch {} finally {24+ controller.abort();25+ }26+};27+28+// @todo: replace with `getDefaultHighWaterMark(true)` after dropping support for Node <18.17.029+export const DEFAULT_OBJECT_HIGH_WATER_MARK = 16;30+31+// The `highWaterMark` of `events.on()` is measured in number of events, not in bytes.32+// Not knowing the average amount of bytes per `data` event, we use the same heuristic as streams in objectMode, since they have the same issue.33+// Therefore, we use the value of `getDefaultHighWaterMark(true)`.34+// Note: this option does not exist on Node 18, but this is ok since the logic works without it. It just consumes more memory.35+const HIGH_WATER_MARK = DEFAULT_OBJECT_HIGH_WATER_MARK;36+37+const iterateOnData = async function * ({subprocessStdout, onStdoutChunk, controller, binary, preserveNewlines}) {38+ const {39+ encodeChunk = identityGenerator,40+ encodeChunkFinal = noopGenerator,41+ splitLines = identityGenerator,42+ splitLinesFinal = noopGenerator,43+ } = getTransforms({subprocessStdout, binary, preserveNewlines});44+45+ try {46+ for await (const [chunk] of onStdoutChunk) {47+ yield * handleChunk(encodeChunk, splitLines, chunk);48+ }49+ } catch (error) {50+ if (!controller.signal.aborted) {51+ throw error;52+ }53+ } finally {54+ yield * handleFinalChunks(encodeChunkFinal, splitLines, splitLinesFinal);55+ }56+};57+58+const getTransforms = ({subprocessStdout, binary, preserveNewlines}) => {59+ if (subprocessStdout.readableObjectMode) {60+ return {};61+ }62+63+ const writableObjectMode = false;64+65+ if (!binary) {66+ return getTextTransforms(binary, preserveNewlines, writableObjectMode);67+ }68+69+ return {};70+};71+72+const getTextTransforms = (binary, preserveNewlines, writableObjectMode) => {73+ const encoding = 'utf8';74+ const {transform: encodeChunk, final: encodeChunkFinal} = getEncodingTransformGenerator(encoding, writableObjectMode, false);75+ const {transform: splitLines, final: splitLinesFinal} = getSplitLinesGenerator({encoding, binary, preserveNewlines, writableObjectMode, state: {}});76+ return {encodeChunk, encodeChunkFinal, splitLines, splitLinesFinal};77+};78+79+const identityGenerator = function * (chunk) {80+ yield chunk;81+};82+83+const noopGenerator = function * () {};84+85+const handleChunk = function * (encodeChunk, splitLines, chunk) {86+ for (const chunkString of encodeChunk(chunk)) {87+ yield * splitLines(chunkString);88+ }89+};90+91+const handleFinalChunks = function * (encodeChunkFinal, splitLines, splitLinesFinal) {92+ for (const chunkString of encodeChunkFinal()) {93+ yield * splitLines(chunkString);94+ }95+96+ yield * splitLinesFinal();97+};modified:lib/convert/readable.js+26 added-37 removed
11234567891011121314141516171819172021192021222324252326272829302 unmodified lines333435363435363738394041424344373839404142434445464847484950515253545556575859606162636465665368545556717257585960616263646566796768697071727374757617 unmodified linesimport {on} from 'node:events';import {Readable} from 'node:stream';import {callbackify} from 'node:util';import {getReadable} from '../pipe/validate.js';import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';import { createDeferred, safeWaitForSubprocessStdin, waitForSubprocessStdout, waitForSubprocess, destroyOtherStream,} from './shared.js';import {iterateOnStdout, DEFAULT_OBJECT_HIGH_WATER_MARK} from './loop.js';
// Create a `Readable` stream that forwards from `stdout` and awaits the subprocessexport const createReadable = ({subprocess, concurrentStreams}, {from} = {}) => {export const createReadable = ({subprocess, concurrentStreams}, {from, binary = true, preserveNewlines = true} = {}) => { const {subprocessStdout, waitReadableDestroy} = getSubprocessStdout(subprocess, from, concurrentStreams); const {readableEncoding, readableObjectMode, readableHighWaterMark} = getReadableOptions(subprocessStdout, binary); const {read, onStdoutDataDone} = getReadableMethods({subprocessStdout, subprocess, binary, preserveNewlines}); const readable = new Readable({ ...getReadableMethods(subprocessStdout, subprocess), read, destroy: callbackify(onReadableDestroy.bind(undefined, {subprocessStdout, subprocess, waitReadableDestroy})), highWaterMark: subprocessStdout.readableHighWaterMark, objectMode: subprocessStdout.readableObjectMode, encoding: subprocessStdout.readableEncoding, highWaterMark: readableHighWaterMark, objectMode: readableObjectMode, encoding: readableEncoding, }); onStdoutFinished(subprocessStdout, readable, subprocess); onStdoutFinished({subprocessStdout, onStdoutDataDone, readable, subprocess}); return readable;};
// Retrieve `stdout` (or other stream depending on `from`)2 unmodified lines const waitReadableDestroy = addConcurrentStream(concurrentStreams, subprocessStdout, 'readableDestroy'); return {subprocessStdout, waitReadableDestroy};};
export const getReadableMethods = (subprocessStdout, subprocess) => { const controller = new AbortController(); stopReadingOnExit(subprocess, controller); const onStdoutData = on(subprocessStdout, 'data', { signal: controller.signal, highWaterMark: HIGH_WATER_MARK, // Backward compatibility with older name for this option // See https://github.com/nodejs/node/pull/52080#discussion_r1525227861 // @todo Remove after removing support for Node 21 highWatermark: HIGH_WATER_MARK, });export const getReadableOptions = ({readableEncoding, readableObjectMode, readableHighWaterMark}, binary) => binary ? {readableEncoding, readableObjectMode, readableHighWaterMark} : {readableEncoding, readableObjectMode: true, readableHighWaterMark: DEFAULT_OBJECT_HIGH_WATER_MARK};
export const getReadableMethods = ({subprocessStdout, subprocess, binary, preserveNewlines}) => { const onStdoutDataDone = createDeferred(); const onStdoutData = iterateOnStdout({subprocessStdout, subprocess, binary, preserveNewlines});
return { read() { onRead(this, onStdoutData); onRead(this, onStdoutData, onStdoutDataDone); }, onStdoutDataDone, };};
const stopReadingOnExit = async (subprocess, controller) => { try { await subprocess; } catch {} finally { controller.abort(); }};
// The `highWaterMark` of `events.on()` is measured in number of events, not in bytes.// Not knowing the average amount of bytes per `data` event, we use the same heuristic as streams in objectMode, since they have the same issue.// Therefore, we use the value of `getDefaultHighWaterMark(true)`.// Note: this option does not exist on Node 18, but this is ok since the logic works without it. It just consumes more memory.const HIGH_WATER_MARK = 16;
// Forwards data from `stdout` to `readable`const onRead = async (readable, onStdoutData) => {const onRead = async (readable, onStdoutData, onStdoutDataDone) => { try { const {value, done} = await onStdoutData.next(); if (!done) { readable.push(value[0]); if (done) { onStdoutDataDone.resolve(); } else { readable.push(value); } } catch {}};
// When `subprocess.stdout` ends/aborts/errors, do the same on `readable`.// Await the subprocess, for the same reason as above.export const onStdoutFinished = async (subprocessStdout, readable, subprocess, subprocessStdin) => {export const onStdoutFinished = async ({subprocessStdout, onStdoutDataDone, readable, subprocess, subprocessStdin}) => { try { await waitForSubprocessStdout(subprocessStdout); await subprocess; await safeWaitForSubprocessStdin(subprocessStdin); await onStdoutDataDone;
if (readable.readable) { readable.push(null); }17 unmodified linesmodified:lib/convert/shared.js+8 added
42 unmodified lines43 } else if (isOpen) {44 stream.destroy();45 }46 };47+48+export const createDeferred = () => {49+ let resolve;50+ const promise = new Promise(resolve_ => {51+ resolve = resolve_;52+ });53+ return Object.assign(promise, {resolve});54+};added:test/convert/loop.js+137 added
1+import {once} from 'node:events';2+import {getDefaultHighWaterMark} from 'node:stream';3+import test from 'ava';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {6+ assertStreamOutput,7+ assertStreamChunks,8+ assertSubprocessOutput,9+ getReadableSubprocess,10+ getReadWriteSubprocess,11+} from '../helpers/convert.js';12+import {13+ simpleFull,14+ simpleChunks,15+ simpleChunksBuffer,16+ simpleLines,17+ noNewlinesFull,18+ complexFull,19+ singleComplexBuffer,20+ complexChunks,21+ complexChunksEnd,22+} from '../helpers/lines.js';23+import {outputObjectGenerator, getOutputGenerator} from '../helpers/generator.js';24+import {foobarString, foobarObject} from '../helpers/input.js';25+import {multibyteChar, multibyteUint8Array, breakingLength, brokenSymbol} from '../helpers/encoding.js';26+27+setFixtureDir();28+29+const foobarObjectChunks = [foobarObject, foobarObject, foobarObject];30+31+const getSubprocess = (methodName, output, options) => {32+ if (methodName !== 'duplex') {33+ return getReadableSubprocess(output, options);34+ }35+36+ const subprocess = getReadWriteSubprocess(options);37+ subprocess.stdin.end(output);38+ return subprocess;39+};40+41+// eslint-disable-next-line max-params42+const testText = async (t, expectedChunks, methodName, binary, preserveNewlines) => {43+ const subprocess = getSubprocess(methodName, complexFull);44+ const stream = subprocess[methodName]({binary, preserveNewlines});45+46+ await assertStreamChunks(t, stream, expectedChunks);47+ await assertSubprocessOutput(t, subprocess, complexFull);48+};49+50+test('.readable() can use "binary: true"', testText, singleComplexBuffer, 'readable', true, undefined);51+test('.readable() can use "binary: undefined"', testText, singleComplexBuffer, 'readable', undefined, undefined);52+test('.readable() can use "binary: false"', testText, complexChunksEnd, 'readable', false, undefined);53+test('.readable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'readable', false, true);54+test('.readable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'readable', false, false);55+test('.duplex() can use "binary: true"', testText, singleComplexBuffer, 'duplex', true, undefined);56+test('.duplex() can use "binary: undefined"', testText, singleComplexBuffer, 'duplex', undefined, undefined);57+test('.duplex() can use "binary: false"', testText, complexChunksEnd, 'duplex', false, undefined);58+test('.duplex() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'duplex', false, true);59+test('.duplex() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'duplex', false, false);60+61+const testTextOutput = async (t, expectedOutput, methodName, preserveNewlines) => {62+ const subprocess = getSubprocess(methodName, complexFull);63+ const stream = subprocess[methodName]({binary: false, preserveNewlines});64+65+ await assertStreamOutput(t, stream, expectedOutput);66+ await assertSubprocessOutput(t, subprocess, complexFull);67+};68+69+test('.readable() "binary: false" keeps output as is', testTextOutput, complexFull, 'readable', undefined);70+test('.readable() "binary: false" + "preserveNewlines: true" keeps output as is', testTextOutput, complexFull, 'readable', true);71+test('.readable() "binary: false" + "preserveNewlines: false" removes all newlines', testTextOutput, noNewlinesFull, 'readable', false);72+test('.duplex() "binary: false" keeps output as is', testTextOutput, complexFull, 'duplex', undefined);73+test('.duplex() "binary: false" + "preserveNewlines: true" keeps output as is', testTextOutput, complexFull, 'duplex', true);74+test('.duplex() "binary: false" + "preserveNewlines: false" removes all newlines', testTextOutput, noNewlinesFull, 'duplex', false);75+76+// eslint-disable-next-line max-params77+const testObjectMode = async (t, expectedChunks, methodName, encoding, initialObjectMode, finalObjectMode, binary, options) => {78+ const subprocess = getSubprocess(methodName, simpleFull, options);79+ if (encoding !== null) {80+ subprocess.stdout.setEncoding(encoding);81+ }82+83+ t.is(subprocess.stdout.readableEncoding, encoding);84+ t.is(subprocess.stdout.readableObjectMode, initialObjectMode);85+ t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));86+87+ const stream = subprocess[methodName]({binary, preserveNewlines: true});88+ t.is(stream.readableEncoding, encoding);89+ t.is(stream.readableObjectMode, finalObjectMode);90+ t.is(stream.readableHighWaterMark, getDefaultHighWaterMark(finalObjectMode));91+ t.is(subprocess.stdout.readableEncoding, encoding);92+ t.is(subprocess.stdout.readableObjectMode, initialObjectMode);93+ t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));94+95+ await assertStreamChunks(t, stream, expectedChunks);96+ await subprocess;97+};98+99+test('.readable() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'readable', null, false, false, true);100+test('.readable() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true);101+test('.readable() uses strings with "binary: true" and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true, {encoding: 'buffer'});102+test('.readable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, true, {stdout: outputObjectGenerator});103+test('.readable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'readable', null, false, true, false);104+test('.readable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'readable', 'utf8', false, true, false);105+test('.readable() uses strings in objectMode with "binary: false" and "encoding: buffer"', testObjectMode, simpleLines, 'readable', 'utf8', false, true, false, {encoding: 'buffer'});106+test('.readable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, false, {stdout: outputObjectGenerator});107+test('.duplex() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'duplex', null, false, false, true);108+test('.duplex() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true);109+test('.duplex() uses strings with "binary: true" and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true, {encoding: 'buffer'});110+test('.duplex() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, true, {stdout: outputObjectGenerator});111+test('.duplex() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'duplex', null, false, true, false);112+test('.duplex() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'duplex', 'utf8', false, true, false);113+test('.duplex() uses strings in objectMode with "binary: false" and "encoding: buffer"', testObjectMode, simpleLines, 'duplex', 'utf8', false, true, false, {encoding: 'buffer'});114+test('.duplex() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, false, {stdout: outputObjectGenerator});115+116+const testObjectSplit = async (t, methodName) => {117+ const subprocess = getSubprocess(methodName, foobarString, {stdout: getOutputGenerator(simpleFull, true)});118+ const stream = subprocess[methodName]({binary: false});119+ await assertStreamChunks(t, stream, [simpleFull]);120+ await subprocess;121+};122+123+test('.readable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'readable');124+test('.duplex() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'duplex');125+126+const testMultibyteCharacters = async (t, methodName) => {127+ const subprocess = getReadWriteSubprocess();128+ const stream = subprocess[methodName]({binary: false});129+ const assertPromise = assertStreamOutput(t, stream, `${multibyteChar}${brokenSymbol}`);130+ subprocess.stdin.write(multibyteUint8Array.slice(0, breakingLength));131+ await once(subprocess.stdout, 'data');132+ subprocess.stdin.end();133+ await assertPromise;134+};135+136+test('.readable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'readable');137+test('.duplex() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'duplex');modified:test/convert/readable.js+9 added-8 removed
1 import {once} from 'node:events';2 import process from 'node:process';3-import {compose, Readable, Writable, PassThrough, getDefaultHighWaterMark} from 'node:stream';3+import {compose, Readable, Writable, PassThrough} from 'node:stream';4 import {pipeline} from 'node:stream/promises';5 import {text} from 'node:stream/consumers';6 import {setTimeout} from 'node:timers/promises';7 import test from 'ava';4 unmodified lines12 assertReadableAborted,13 assertWritableAborted,14 assertProcessNormalExit,15 assertStreamOutput,16+ assertStreamChunks,17 assertStreamError,18 assertStreamReadError,19 assertSubprocessOutput,20 assertSubprocessError,226 unmodified lines247 const stream = subprocess.readable();248 t.true(stream.readableObjectMode);249 t.is(stream.readableHighWaterMark, defaultObjectHighWaterMark);250 250- t.deepEqual(await stream.toArray(), [foobarObject]);251+ await assertStreamChunks(t, stream, [foobarObject]);252 await assertSubprocessOutput(t, subprocess, [foobarObject]);253 });254 255 test('.duplex() works with objectMode and reads', async t => {4 unmodified lines260 t.false(stream.writableObjectMode);261 t.is(stream.writableHighWaterMark, defaultHighWaterMark);262 stream.end(foobarString);263 263- t.deepEqual(await stream.toArray(), [foobarObject]);264+ await assertStreamChunks(t, stream, [foobarObject]);265 await assertSubprocessOutput(t, subprocess, [foobarObject]);266 });267 268 test('.readable() works with default encoding', async t => {269 const subprocess = getReadableSubprocess();270 const stream = subprocess.readable();271 t.is(stream.readableEncoding, null);272 272- t.deepEqual(await stream.toArray(), [foobarBuffer]);273+ await assertStreamChunks(t, stream, [foobarBuffer]);274 await assertSubprocessOutput(t, subprocess, foobarString);275 });276 277 test('.duplex() works with default encoding', async t => {1 unmodified line279 const stream = subprocess.duplex();280 t.is(stream.readableEncoding, null);281 stream.end(foobarString);282 282- t.deepEqual(await stream.toArray(), [foobarBuffer]);283+ await assertStreamChunks(t, stream, [foobarBuffer]);284 await assertSubprocessOutput(t, subprocess, foobarString);285 });286 287 test('.readable() works with encoding "utf8"', async t => {1 unmodified line289 subprocess.stdout.setEncoding('utf8');290 const stream = subprocess.readable();291 t.is(stream.readableEncoding, 'utf8');292 292- t.deepEqual(await stream.toArray(), [foobarString]);293+ await assertStreamChunks(t, stream, [foobarString]);294 await assertSubprocessOutput(t, subprocess, foobarString);295 });296 297 test('.duplex() works with encoding "utf8"', async t => {2 unmodified lines300 const stream = subprocess.duplex();301 t.is(stream.readableEncoding, 'utf8');302 stream.end(foobarBuffer);303 303- t.deepEqual(await stream.toArray(), [foobarString]);304+ await assertStreamChunks(t, stream, [foobarString]);305 await assertSubprocessOutput(t, subprocess, foobarString);306 });307 308 test('.readable() has the right highWaterMark', async t => {119 unmodified lines428 // eslint-disable-next-line no-await-in-loop429 await Promise.race([onPause, once(subprocess.stdout, 'data')]);430 }431 431- const expectedCount = getDefaultHighWaterMark(true) + 1;432+ const expectedCount = defaultObjectHighWaterMark + 1;433 const expectedOutput = '.'.repeat(expectedCount);434 t.is(count, expectedCount);435 subprocess.stdin.end();436 await assertStreamOutput(t, stream, expectedOutput);19 unmodified linesmodified:test/helpers/convert.js+5 added-1 removed
25 unmodified lines26 export const assertStreamOutput = async (t, stream, expectedOutput = foobarString) => {27 t.is(await text(stream), expectedOutput);28 };29 30+export const assertStreamChunks = async (t, stream, expectedOutput) => {31+ t.deepEqual(await stream.toArray(), expectedOutput);32+};33+34 export const assertSubprocessOutput = async (t, subprocess, expectedOutput = foobarString, fdNumber = 1) => {35 const result = await subprocess;36 t.deepEqual(result.stdio[fdNumber], expectedOutput);37 };15 unmodified lines53 54 return thrownError;55 };56 53-export const getReadableSubprocess = () => execa('noop-fd.js', ['1', foobarString]);57+export const getReadableSubprocess = (output = foobarString, options = {}) => execa('noop-fd.js', ['1', output], options);58 59 export const getWritableSubprocess = () => execa('noop-stdin-fd.js', ['2']);60 61 export const getReadWriteSubprocess = options => execa('stdin.js', options);added:test/helpers/encoding.js+7 added
1234567const textEncoder = new TextEncoder();
export const multibyteChar = '\u{1F984}';export const multibyteString = `${multibyteChar}${multibyteChar}`;export const multibyteUint8Array = textEncoder.encode(multibyteString);export const breakingLength = multibyteUint8Array.length * 0.75;export const brokenSymbol = '\uFFFD';modified:test/helpers/lines.js+6 added
1 import {Buffer} from 'node:buffer';2 3 export const simpleFull = 'aaa\nbbb\nccc';4 export const simpleChunks = [simpleFull];5+export const simpleChunksBuffer = [Buffer.from(simpleFull)];6 export const simpleLines = ['aaa\n', 'bbb\n', 'ccc'];7 export const simpleFullEndLines = ['aaa\n', 'bbb\n', 'ccc\n'];8+export const noNewlinesFull = 'aaabbbccc';9 export const noNewlinesChunks = ['aaa', 'bbb', 'ccc'];10+export const complexFull = '\naaa\r\nbbb\n\nccc';11+export const singleComplexBuffer = [Buffer.from(complexFull)];12+export const complexChunksEnd = ['\n', 'aaa\r\n', 'bbb\n', '\n', 'ccc'];13+export const complexChunks = ['', 'aaa', 'bbb', '', 'ccc'];14 15 const textEncoder = new TextEncoder();16 const textDecoder = new TextDecoder();17 17 unmodified linesmodified:test/stdio/encoding-transform.js+1 added-8 removed
4 unmodified lines5 import {setFixtureDir} from '../helpers/fixtures-dir.js';6 import {getStdio} from '../helpers/stdio.js';7 import {foobarString, foobarUint8Array, foobarBuffer, foobarObject} from '../helpers/input.js';8 import {noopGenerator, getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';9+import {multibyteChar, multibyteString, multibyteUint8Array, breakingLength, brokenSymbol} from '../helpers/encoding.js';10 11 setFixtureDir();12 12-const textEncoder = new TextEncoder();13-13 const getTypeofGenerator = (objectMode, binary) => ({14 * transform(line) {15 yield Object.prototype.toString.call(line);16 },136 unmodified lines153 test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true);154 test('Generator can return final string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, true);155 test('Generator can return final Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, true);156 158-const multibyteChar = '\u{1F984}';159-const multibyteString = `${multibyteChar}${multibyteChar}`;160-const multibyteUint8Array = textEncoder.encode(multibyteString);161-const breakingLength = multibyteUint8Array.length * 0.75;162-const brokenSymbol = '\uFFFD';163-157 const testMultibyte = async (t, objectMode) => {158 const subprocess = execa('stdin.js', {stdin: noopGenerator(objectMode, true)});159 subprocess.stdin.write(multibyteUint8Array.slice(0, breakingLength));160 await scheduler.yield();20 unmodified linesmodified:test/stdio/split.js+1 added-1 removed
12 unmodified lines13 simpleFull,14 simpleChunks,15 simpleLines,16 simpleFullEndLines,17+ noNewlinesFull,18 noNewlinesChunks,19 getEncoding,20 stringsToUint8Arrays,21 serializeResult,6 unmodified lines28 const windowsFull = 'aaa\r\nbbb\r\nccc';29 const windowsFullEnd = `${windowsFull}\r\n`;30 const windowsChunks = [windowsFull];31 const windowsLines = ['aaa\r\n', 'bbb\r\n', 'ccc'];31-const noNewlinesFull = 'aaabbbccc';32 const noNewlinesFullEnd = `${noNewlinesFull}\n`;33 const noNewlinesLines = ['aaabbbccc'];34 const singleFull = 'aaa';35 const singleFullEnd = `${singleFull}\n`;293 unmodified linesmodified:index.d.ts+26 added-6 removed
976 unmodified lines977 pipe<Destination extends ExecaSubprocess>(destination: Destination, options?: PipeOptions):978 Promise<Awaited<Destination>> & PipableSubprocess;979 };980 981-type ReadableStreamOptions = {981+type ReadableOptions = {982 /**983 Which stream to read from the subprocess. A file descriptor like `"fd3"` can also be passed.984 985 `"all"` reads both `stdout` and `stderr`. This requires the `all` option to be `true`.986+987+ @default 'stdout'988 */989 readonly from?: FromOption;990+991+ /**992+ If `false`, the stream iterates over lines. Each line is a string. Also, the stream is in [object mode](https://nodejs.org/api/stream.html#object-mode).993+994+ If `true`, the stream iterates over arbitrary chunks of data. Each line is a [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer).995+996+ @default true997+ */998+ readonly binary?: boolean;999+1000+ /**1001+ If both this option and the `binary` option is `false`, newlines are stripped from each line.1002+1003+ @default true1004+ */1005+ readonly preserveNewlines?: boolean;1006 };1007 990-type WritableStreamOptions = {1008+type WritableOptions = {1009 /**1010 Which stream to write to the subprocess. A file descriptor like `"fd3"` can also be passed.1011+1012+ @default 'stdin'1013 */1014 readonly to?: ToOption;1015 };1016 997-type DuplexStreamOptions = ReadableStreamOptions & WritableStreamOptions;1017+type DuplexOptions = ReadableOptions & WritableOptions;1018 1019 export type ExecaResultPromise<OptionsType extends Options = Options> = {1020 stdin: StreamUnlessIgnored<'0', OptionsType>;1021 32 unmodified lines1054 Unlike [`subprocess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout), the stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess fails. This means you do not need to `await` the subprocess' promise. On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options), [`await pipeline(..., stream)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) or [`await text(stream)`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) which throw an exception when the stream errors.1055 1056 Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options or the `subprocess.pipe()` method.1057 */1038- readable(streamOptions?: ReadableStreamOptions): Readable;1058+ readable(readableOptions?: ReadableOptions): Readable;1059 1060 /**1061 Converts the subprocess to a writable stream.1062 1063 Unlike [`subprocess.stdin`](https://nodejs.org/api/child_process.html#subprocessstdin), the stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess fails. This means you do not need to `await` the subprocess' promise. On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options) or [`await pipeline(stream, ...)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) which throw an exception when the stream errors.1064 1065 Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options or the `subprocess.pipe()` method.1066 */1047- writable(streamOptions?: WritableStreamOptions): Writable;1067+ writable(writableOptions?: WritableOptions): Writable;1068 1069 /**1070 Converts the subprocess to a duplex stream.1071 1072 The stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess fails. This means you do not need to `await` the subprocess' promise. On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options), [`await pipeline(..., stream, ...)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) or [`await text(stream)`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) which throw an exception when the stream errors.1073 1074 Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options or the `subprocess.pipe()` method.1075 */1056- duplex(streamOptions?: DuplexStreamOptions): Duplex;1076+ duplex(duplexOptions?: DuplexOptions): Duplex;1077 } & PipableSubprocess;1078 1079 export type ExecaSubprocess<OptionsType extends Options = Options> = ChildProcess &1080 ExecaResultPromise<OptionsType> &475 unmodified linesmodified:index.test-d.ts+12 added
275 unmodified lines276 scriptPromise.readable({from: 'stdout'});277 scriptPromise.readable({from: 'stderr'});278 scriptPromise.readable({from: 'all'});279 scriptPromise.readable({from: 'fd3'});280+ scriptPromise.readable({binary: false});281+ scriptPromise.readable({preserveNewlines: false});282 expectError(scriptPromise.readable('stdout'));283 expectError(scriptPromise.readable({from: 'stdin'}));284 expectError(scriptPromise.readable({from: 'fd'}));285 expectError(scriptPromise.readable({from: 'fdNotANumber'}));286+ expectError(scriptPromise.readable({binary: 'false'}));287+ expectError(scriptPromise.readable({preserveNewlines: 'false'}));288+ expectError(scriptPromise.readable({to: 'stdin'}));289 expectError(scriptPromise.readable({other: 'stdout'}));290 scriptPromise.writable({});291 scriptPromise.writable({to: 'stdin'});292 scriptPromise.writable({to: 'fd3'});293 expectError(scriptPromise.writable('stdin'));294 expectError(scriptPromise.writable({to: 'stdout'}));295 expectError(scriptPromise.writable({to: 'fd'}));296 expectError(scriptPromise.writable({to: 'fdNotANumber'}));297+ expectError(scriptPromise.writable({from: 'stdout'}));298+ expectError(scriptPromise.writable({binary: false}));299+ expectError(scriptPromise.writable({preserveNewlines: false}));300 expectError(scriptPromise.writable({other: 'stdin'}));301 scriptPromise.duplex({});302 scriptPromise.duplex({from: 'stdout'});303 scriptPromise.duplex({from: 'stderr'});304 scriptPromise.duplex({from: 'all'});305 scriptPromise.duplex({from: 'fd3'});306 scriptPromise.duplex({from: 'stdout', to: 'stdin'});307 scriptPromise.duplex({from: 'stdout', to: 'fd3'});308+ scriptPromise.duplex({binary: false});309+ scriptPromise.duplex({preserveNewlines: false});310 expectError(scriptPromise.duplex('stdout'));311 expectError(scriptPromise.duplex({from: 'stdin'}));312 expectError(scriptPromise.duplex({from: 'stderr', to: 'stdout'}));313 expectError(scriptPromise.duplex({from: 'fd'}));314 expectError(scriptPromise.duplex({from: 'fdNotANumber'}));315 expectError(scriptPromise.duplex({to: 'fd'}));316 expectError(scriptPromise.duplex({to: 'fdNotANumber'}));317+ expectError(scriptPromise.duplex({binary: 'false'}));318+ expectError(scriptPromise.duplex({preserveNewlines: 'false'}));319 expectError(scriptPromise.duplex({other: 'stdout'}));320 321 expectType<Readable>(execaPromise.all);322 const noAllPromise = execa('unicorns');1350 unmodified linesmodified:readme.md+29 added-13 removed
436 unmodified lines437 When an error is passed as argument, it is set to the subprocess' [`error.cause`](#cause). The subprocess is then terminated with the default signal. This does not emit the [`error` event](https://nodejs.org/api/child_process.html#event-error).438 439 [More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)440 441-#### readable(streamOptions?)441+#### readable(readableOptions?)442 443-`streamOptions`: [`StreamOptions`](#streamoptions)\443+`readableOptions`: [`ReadableOptions`](#readableoptions)\444 _Returns_: [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable) Node.js stream445 446 Converts the subprocess to a readable stream.447 448 Unlike [`subprocess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout), the stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess [fails](#subprocessresult). This means you do not need to `await` the subprocess' [promise](#subprocess). On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options), [`await pipeline(..., stream)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) or [`await text(stream)`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) which throw an exception when the stream errors.449 450 Before using this method, please first consider the [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1)/[`stdio`](#stdio-1) options or the [`subprocess.pipe()`](#pipefile-arguments-options) method.451 452-#### writable(streamOptions?)452+#### writable(writableOptions?)453 454-`streamOptions`: [`StreamOptions`](#streamoptions)\454+`writableOptions`: [`WritableOptions`](#writableoptions)\455 _Returns_: [`Writable`](https://nodejs.org/api/stream.html#class-streamwritable) Node.js stream456 457 Converts the subprocess to a writable stream.458 459 Unlike [`subprocess.stdin`](https://nodejs.org/api/child_process.html#subprocessstdin), the stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess [fails](#subprocessresult). This means you do not need to `await` the subprocess' [promise](#subprocess). On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options) or [`await pipeline(stream, ...)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) which throw an exception when the stream errors.460 461 Before using this method, please first consider the [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1)/[`stdio`](#stdio-1) options or the [`subprocess.pipe()`](#pipefile-arguments-options) method.462 463-#### duplex(streamOptions?)463+#### duplex(duplexOptions?)464 465-`streamOptions`: [`StreamOptions`](#streamoptions)\465+`duplexOptions`: [`ReadableOptions | WritableOptions`](#readableoptions)\466 _Returns_: [`Duplex`](https://nodejs.org/api/stream.html#class-streamduplex) Node.js stream467 468 Converts the subprocess to a duplex stream.469 470 The stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess [fails](#subprocessresult). This means you do not need to `await` the subprocess' [promise](#subprocess). On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options), [`await pipeline(..., stream, ...)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) or [`await text(stream)`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) which throw an exception when the stream errors.471 472 Before using this method, please first consider the [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1)/[`stdio`](#stdio-1) options or the [`subprocess.pipe()`](#pipefile-arguments-options) method.473 474-##### streamOptions474+##### readableOptions475 476 Type: `object`477 478-##### streamOptions.from478+##### readableOptions.from479 480 Type: `"stdout" | "stderr" | "all" | "fd3" | "fd4" | ...`\481 Default: `"stdout"`482 483 Which stream to read from the subprocess. A file descriptor like `"fd3"` can also be passed.484 485 `"all"` reads both `stdout` and `stderr`. This requires the [`all` option](#all-2) to be `true`.486 487-Only available with [`.readable()`](#readablestreamoptions) and [`.duplex()`](#duplexstreamoptions), not [`.writable()`](#writablestreamoptions).487+##### readableOptions.binary488 489-##### streamOptions.to489+Type: `boolean`\490+Default: `true`491 492+If `false`, the stream iterates over lines. Each line is a string. Also, the stream is in [object mode](https://nodejs.org/api/stream.html#object-mode).493+494+If `true`, the stream iterates over arbitrary chunks of data. Each line is a [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer).495+496+##### readableOptions.preserveNewlines497+498+Type: `boolean`\499+Default: `true`500+501+If both this option and the [`binary` option](#readableoptionsbinary) is `false`, newlines are stripped from each line.502+503+##### writableOptions504+505+Type: `object`506+507+##### writableOptions.to508+509 Type: `"stdin" | "fd3" | "fd4" | ...`\510 Default: `"stdin"`511 512 Which stream to write to the subprocess. A file descriptor like `"fd3"` can also be passed.513 496-Only available with [`.writable()`](#writablestreamoptions) and [`.duplex()`](#duplexstreamoptions), not [`.readable()`](#readablestreamoptions).497-514 ### SubprocessResult515 516 Type: `object`517 398 unmodified lines916 Default: `false`917 918 Split `stdout` and `stderr` into lines.919 - [`result.stdout`](#stdout), [`result.stderr`](#stderr), [`result.all`](#all-1) and [`result.stdio`](#stdio) are arrays of lines.904-- [`subprocess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout), [`subprocess.stderr`](https://nodejs.org/api/child_process.html#subprocessstderr), [`subprocess.all`](#all), [`subprocess.stdio`](https://nodejs.org/api/child_process.html#subprocessstdio), [`subprocess.readable()`](#readablestreamoptions) and [`subprocess.duplex`](#duplexstreamoptions) iterate over lines instead of arbitrary chunks.920+- [`subprocess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout), [`subprocess.stderr`](https://nodejs.org/api/child_process.html#subprocessstderr), [`subprocess.all`](#all), [`subprocess.stdio`](https://nodejs.org/api/child_process.html#subprocessstdio), [`subprocess.readable()`](#readablereadableoptions) and [`subprocess.duplex`](#duplexduplexoptions) iterate over lines instead of arbitrary chunks.921 - Any stream passed to the [`stdout`](#stdout-1), [`stderr`](#stderr-1) or [`stdio`](#stdio-1) option receives lines instead of arbitrary chunks.922 923 #### encoding924 258 unmodified lines