diff --git a/README.md b/README.md index 71d4086..8e1076e 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,17 @@ await write("./example-project\n"); await exit(); ``` +To capture each output chunk one-by-one, you can use `onData` callback. +This can be useful when debugging output of the stream. + +```ts +const { isDone, onData } = webcontainer.runCommand("npm", ["run", "build"]); + +onData((chunk) => console.log(chunk)); + +await isDone; +``` + ##### `readFile` WebContainer's [`readFile`](https://webcontainers.io/guides/working-with-the-file-system#readfile) method. diff --git a/src/fixtures/process.ts b/src/fixtures/process.ts index 95274a0..c17425d 100644 --- a/src/fixtures/process.ts +++ b/src/fixtures/process.ts @@ -11,7 +11,7 @@ export class ProcessWrap { private _output: string = ""; /** @internal */ - private _listeners: (() => void)[] = []; + private _listeners: ((chunk: string) => void)[] = []; /** @internal */ private _writer?: ReturnType; @@ -35,7 +35,7 @@ export class ProcessWrap { new WritableStream({ write: (data) => { this._output += data; - this._listeners.forEach((fn) => fn()); + this._listeners.forEach((fn) => fn(data)); }, }), ); @@ -109,6 +109,13 @@ export class ProcessWrap { }); }; + /** + * Listen for data stream chunks. + */ + onData = (listener: (chunk: string) => void) => { + this._listeners.push(listener); + }; + /** * Exit the process. */ diff --git a/test/run-command.test.ts b/test/run-command.test.ts index 410d648..bcb7f2e 100644 --- a/test/run-command.test.ts +++ b/test/run-command.test.ts @@ -43,3 +43,22 @@ test("user can see timeout errors with clear description", async ({ await exit(); }); + +test("user can listen for stream's chunks", async ({ webcontainer }) => { + const { isDone, onData } = webcontainer.runCommand("node", [ + "--eval", + "console.log('First'); setTimeout(() => console.log('Second'), 1_000);", + ]); + + const data: string[] = []; + onData((chunk) => data.push(chunk.trim())); + + await isDone; + + expect(data).toMatchInlineSnapshot(` + [ + "First", + "Second", + ] + `); +});