@mountainpass/hooked-cli
Version:
A tool for runnable scripts
38 lines (37 loc) • 1.2 kB
JavaScript
import { Writable } from "stream";
// A class that captures output while also passing it through to the original stream
export class CaptureStream extends Writable {
constructor(originalStream, options) {
super(options);
this.originalStream = originalStream;
this.captureBuffer = '';
this.finished = false;
// Listen for the finish event
this.on('finish', () => {
this.finished = true;
this.whenFinished(this.captureBuffer);
});
}
whenUpdated(captured) {
// NOOP used for testing
}
whenFinished(captured) {
// NOOP used for testing
}
_write(chunk, encoding, callback) {
// Convert the chunk to a string
const chunkStr = chunk.toString();
// Capture the chunk
this.captureBuffer += chunkStr;
this.whenUpdated(this.captureBuffer);
// Pass the chunk through to the original stream
if (this.originalStream) {
this.originalStream.write(chunkStr);
}
// Call the callback to signal that writing is complete
callback();
}
getCaptured() {
return this.captureBuffer;
}
}