DEV Community

Yuki Shindo
Yuki Shindo

Posted on

3 2

How to read keystrokes from stdin at Deno

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);
Enter fullscreen mode Exit fullscreen mode

If you want to use Deno.setRaw, you need to run it with the --unstable option.

deno run --unstable sample.ts
Enter fullscreen mode Exit fullscreen mode

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 + C to finish the process.
  • Pressing the Enter key will do the same, but the process will end after outputting the string from the variable of output.
  • I haven't been able to track when the nread variable returns null, but since there is a possibility that it will return null, I've included the processing for that.
  • There is no particular reason for the bufferSize to be 16.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs