Skip to content

Instantly share code, notes, and snippets.

@rcmedeiros
Created March 20, 2020 05:36
Show Gist options
  • Save rcmedeiros/821d63f333c4ec13d50ac39baafc8574 to your computer and use it in GitHub Desktop.
Save rcmedeiros/821d63f333c4ec13d50ac39baafc8574 to your computer and use it in GitHub Desktop.
Capture stdout with callback
import { WriteStream } from 'tty';
type callback = (error: Error | null | undefined) => void;
export const captureStream = (stream: WriteStream, nextLines: number, ccb: (data: string) => void): void => {
const oldWrite = stream.write;
let output = '';
let lines = 0;
stream.write = (chunk: unknown, encoding: string | callback, cb?: callback): boolean => {
const c = chunk.toString();
for (let i = 0; i < c.length; i++) {
if (c[i] === '\n') {
lines++;
}
}
output += c;
const r = oldWrite.apply(stream, cb ? [chunk, encoding, cb] : [chunk, encoding, cb]);
if (lines >= nextLines) {
stream.write = oldWrite;
ccb(output);
}
return r;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment