aboutsummaryrefslogtreecommitdiff
path: root/test/bun.js/spawn-streaming-stdin.test.ts
blob: 6424eadfcc53124a2697633996a8cb0f873fdc1e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { it, test, expect } from "bun:test";
import { spawn } from "bun";
import { bunExe } from "./bunExe";
import { gcTick } from "gc";

const N = 100;
test("spawn can write to stdin multiple chunks", async () => {
  for (let i = 0; i < N; i++) {
    var exited;
    await (async function () {
      const proc = spawn({
        cmd: [bunExe(), import.meta.dir + "/stdin-repro.js"],
        stdout: "pipe",
        stdin: "pipe",
        stderr: Bun.file("/tmp/out.log"),
        env: {
          BUN_DEBUG_QUIET_LOGS: 1,
        },
      });
      // (async function () {
      //   for await (var chunk of proc.stderr) {
      //     console.error("[stderr]", new TextDecoder().decode(chunk));
      //   }
      // })();
      exited = proc.exited;
      var counter = 0;
      var inCounter = 0;
      const prom2 = (async function () {
        while (true) {
          await new Promise((resolve, reject) => setTimeout(resolve, 8));
          proc.stdin.write("Wrote to stdin!");
          inCounter++;

          if (inCounter === 4) break;
        }
        await new Promise((resolve) =>
          Promise.resolve(proc.stdin.end()).then(resolve),
        );
      })();

      var chunks = [];
      const prom = (async function () {
        try {
          for await (var chunk of proc.stdout) {
            chunks.push(chunk);
            counter++;

            if (counter === 4) break;
          }
        } catch (e) {
          console.log(e.stack);
          throw e;
        }
      })();
      await Promise.all([prom, prom2]);
      const code = await exited;
      console.log(code);
      expect(counter).toBe(4);
      expect(Buffer.concat(chunks).toString().trim()).toBe(
        "Wrote to stdin!\n".repeat(4).trim(),
      );
      //   proc.kill();

      gcTick(true);
    })();
  }
});