UNPKG

@mountainpass/hooked-cli

Version:
39 lines (38 loc) 1.25 kB
import { Writable } from "stream"; // A class that captures output while also passing it through to the original stream export class CaptureWritableStream extends Writable { constructor(originalStream, options) { super(options); /** To store captured output. */ this.captureBuffer = ''; this.finished = false; this.originalStream = originalStream; // 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; } }