When using Deno, there was a case where I wanted to process input one character at a time.
I don't fully understand the code yet, so the code itself could be improved, but this is how it worked.
Deno.setRaw(0, true);
const bufferSize = 16;
const buf = new Uint8Array(bufferSize);
let output = "";
while (true) {
  const nread = await Deno.stdin.read(buf);
  if (nread === null) {
    console.log("nread is null");
    console.log("Exit");
    break;
  }
  // If you press Ctrl + C, the process will exit.
  if (buf && buf[0] === 0x03) {
    console.log("Ctrl+C");
    console.log("Exit");
    break;
  }
  // If the Enter key is pressed,
  // the text of the output will be displayed and the process will be terminated.
  if (buf && buf[0] === 13) {
    console.log("Ouput: ", output);
    break;
  }
  const text = new TextDecoder().decode(buf.subarray(0, nread));
  output = output + text;
  console.log(output);
}
Deno.setRaw(0, false);
If you want to use Deno.setRaw, you need to run it with the --unstable option.
deno run --unstable sample.ts
Here are some additional explanations for the code above.
- One by one, the entered characters will be added to the variable of 
output. - Press 
Ctrl + Cto finish the process. - Pressing the 
Enterkey will do the same, but the process will end after outputting the string from the variable ofoutput. - I haven't been able to track when the 
nreadvariable returnsnull, but since there is a possibility that it will returnnull, I've included the processing for that. - There is no particular reason for the 
bufferSizeto be16. 
    
Top comments (0)