bjorn3 / browser_wasi_shim

A WASI shim for in the browser
Apache License 2.0
307 stars 41 forks source link

Include `ConsoleStdout` for incremental output? #66

Closed amesgen closed 9 months ago

amesgen commented 9 months ago

I find ConsoleStdout from an existing test very useful to incrementally get log output while running WASI programs that use stdout/stderr:

https://github.com/bjorn3/browser_wasi_shim/blob/b18b2da1f1410f9483ad322703a3a443202ab69d/test/adapters/browser/run-test.html#L4-L33

In particular, in conjunction with an additional static method

  static lineBuffered(write) {
    const dec = new TextDecoder("utf-8", { fatal: false });
    let line_buf = "";
    return new ConsoleStdout((buffer) => {
      line_buf += dec.decode(buffer, { stream: true });
      const lines = line_buf.split("\n");
      for (const [i, line] of lines.entries()) {
        if (i < lines.length - 1) {
          write(line);
        } else {
          line_buf = line;
        }
      }
    });
  }

which can eg be used like this

[
  new OpenFile(new File([])), // stdin
  ConsoleStdout.lineBuffered(msg => console.log(`[WASI stdout] ${msg}`)),
  ConsoleStdout.lineBuffered(msg => console.warn(`[WASI stderr] ${msg}`)),
]

Is it in scope to add this to the library such that it can be reused by other projects? If so, happy to create a PR.

bjorn3 commented 9 months ago

Yeah, seems useful to have.