Skip to content

Commit 9784b75

Browse files
authored
feat: add process.onData (#13)
1 parent 0fcb624 commit 9784b75

File tree

3 files changed

+39
-2
lines changed

3 files changed

+39
-2
lines changed

README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,17 @@ await write("./example-project\n");
155155
await exit();
156156
```
157157

158+
To capture each output chunk one-by-one, you can use `onData` callback.
159+
This can be useful when debugging output of the stream.
160+
161+
```ts
162+
const { isDone, onData } = webcontainer.runCommand("npm", ["run", "build"]);
163+
164+
onData((chunk) => console.log(chunk));
165+
166+
await isDone;
167+
```
168+
158169
##### `readFile`
159170

160171
WebContainer's [`readFile`](https://webcontainers.io/guides/working-with-the-file-system#readfile) method.

src/fixtures/process.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ export class ProcessWrap {
1111
private _output: string = "";
1212

1313
/** @internal */
14-
private _listeners: (() => void)[] = [];
14+
private _listeners: ((chunk: string) => void)[] = [];
1515

1616
/** @internal */
1717
private _writer?: ReturnType<WebContainerProcess["input"]["getWriter"]>;
@@ -35,7 +35,7 @@ export class ProcessWrap {
3535
new WritableStream({
3636
write: (data) => {
3737
this._output += data;
38-
this._listeners.forEach((fn) => fn());
38+
this._listeners.forEach((fn) => fn(data));
3939
},
4040
}),
4141
);
@@ -109,6 +109,13 @@ export class ProcessWrap {
109109
});
110110
};
111111

112+
/**
113+
* Listen for data stream chunks.
114+
*/
115+
onData = (listener: (chunk: string) => void) => {
116+
this._listeners.push(listener);
117+
};
118+
112119
/**
113120
* Exit the process.
114121
*/

test/run-command.test.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,22 @@ test("user can see timeout errors with clear description", async ({
4343

4444
await exit();
4545
});
46+
47+
test("user can listen for stream's chunks", async ({ webcontainer }) => {
48+
const { isDone, onData } = webcontainer.runCommand("node", [
49+
"--eval",
50+
"console.log('First'); setTimeout(() => console.log('Second'), 1_000);",
51+
]);
52+
53+
const data: string[] = [];
54+
onData((chunk) => data.push(chunk.trim()));
55+
56+
await isDone;
57+
58+
expect(data).toMatchInlineSnapshot(`
59+
[
60+
"First",
61+
"Second",
62+
]
63+
`);
64+
});

0 commit comments

Comments
 (0)