Skip to content

Streaming subprocess output over websocket #17942

Answered by iitzkube
itmecho asked this question in Q&A

You must be logged in to vote

@itmecho I just came across your post! In case you're still looking for an answer two weeks later, here it is :)

When you iterate over cmd.stderr, you get back a buffer chunk, which may be a line, multiple lines, half a line, you don't know.... Therefore, you need to implement a basic line reader like this:

const cmd = Bun.spawn(["some-command", "arg1", "arg2"], {
  stderr: "pipe",
  onExit: () => {
    ws.close(10003, 'program exited');
  },
});

const reader = cmd.stderr.pipeThrough(new TextDecoderStream()).getReader();

let remainder = '';
while (true) {
  const { done, value } = await reader.read();
  if (done) {
    break;
  }
  const lines = (remainder + value).split('\n');
  remainder

Replies: 1 comment 1 reply

You must be logged in to vote
1 reply
@itmecho

Answer selected by itmecho
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants