Skip to content

Commit

Permalink
Improve promise.stdout error handling (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky authored Aug 27, 2024
1 parent 5073e71 commit 6567f40
Show file tree
Hide file tree
Showing 3 changed files with 254 additions and 91 deletions.
8 changes: 4 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ export default function nanoSpawn(file, commandArguments = [], options = {}) {
const subprocess = spawn(...escapeArguments(file, commandArguments, forcedShell), spawnOptions);

useInput(subprocess, input);
const promise = getResult(subprocess, start, command);
const resultPromise = getResult(subprocess, start, command);

const stdoutLines = lineIterator(subprocess.stdout);
const stderrLines = lineIterator(subprocess.stderr);
return Object.assign(promise, {
const stdoutLines = lineIterator(subprocess.stdout, resultPromise);
const stderrLines = lineIterator(subprocess.stderr, resultPromise);
return Object.assign(resultPromise, {
subprocess,
[Symbol.asyncIterator]: () => combineAsyncIterators(stdoutLines, stderrLines),
stdout: stdoutLines,
Expand Down
24 changes: 14 additions & 10 deletions iterable.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,23 @@ export async function * combineAsyncIterators(iterator1, iterator2) {
}
}

export async function * lineIterator(iterable) {
if (!iterable) {
export async function * lineIterator(stream, resultPromise) {
if (!stream) {
return;
}

let buffer = '';
for await (const chunk of iterable) {
const lines = `${buffer}${chunk}`.split(/\r?\n/);
buffer = lines.pop(); // Keep last line in buffer as it may not be complete
yield * lines;
}
try {
let buffer = '';
for await (const chunk of stream.iterator({destroyOnReturn: false})) {
const lines = `${buffer}${chunk}`.split(/\r?\n/);
buffer = lines.pop(); // Keep last line in buffer as it may not be complete
yield * lines;
}

if (buffer) {
yield buffer; // Yield any remaining data as the last line
if (buffer) {
yield buffer; // Yield any remaining data as the last line
}
} finally {
await resultPromise;
}
}
Loading

0 comments on commit 6567f40

Please sign in to comment.