📜  deno stdin (1)

📅  最后修改于: 2023-12-03 15:30:26.283000             🧑  作者: Mango

Deno stdin

Deno is a secure runtime for JavaScript and TypeScript. With the Deno.stdin module, you can read input from the standard input, or stdin, of your program.

How to use Deno stdin

To use the Deno.stdin module, you can use the following code snippet:

async function readStdin(): Promise<string> {
  const buf = new Uint8Array(1024);
  const n = await Deno.stdin.read(buf);
  return new TextDecoder().decode(buf.subarray(0, n)).trim();
}

const input = await readStdin();
console.log(`The user typed: ${input}`);

Here, we create an async function readStdin() that reads input from the standard input and returns it as a string. To do this, we first create a buffer of bytes with new Uint8Array(1024). This buffer has a size of 1024 bytes, which should be sufficient for most cases.

We then use the Deno.stdin.read(buf) method to read input from the stdin and store it in buf. This method returns a Promise that resolves when input is available. The number of bytes read is stored in the n variable.

Finally, we use the TextDecoder().decode(buf.subarray(0, n)).trim() method to convert the buffer into a string and remove any trailing whitespace. We then return this string.

You can call the readStdin() function and assign its result to a variable to get the input from stdin. In this example, we assign the input to the input variable and log it to the console.

Conclusion

With the Deno stdin module, you can easily read input from the standard input of your Deno program. By using the Deno.stdin.read() method, you can read input asynchronously and convert it into a string. This is a useful tool for building command-line utilities and interactive programs.