Created
March 20, 2020 05:36
-
-
Save rcmedeiros/821d63f333c4ec13d50ac39baafc8574 to your computer and use it in GitHub Desktop.
Capture stdout with callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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