从 Deno stdin 获取值

ben*_*pon 13 deno

我们如何从 Deno 的标准输入中获取值?

我不知道怎么用Deno.stdin

一个例子将不胜感激。

Kev*_*ian 7

Deno.stdin是类型File,因此您可以通过提供Uint8Arrayas 缓冲区并调用来读取它Deno.stdin.read(buf)

window.onload = async function main() {
  const buf = new Uint8Array(1024);
  /* Reading into `buf` from start.
   * buf.subarray(0, n) is the read result.
   * If n is instead Deno.EOF, then it means that stdin is closed.
   */
  const n = await Deno.stdin.read(buf); 
  if (n == Deno.EOF) {
    console.log("Standard input closed")
  } else {
    console.log("READ:", new TextDecoder().decode(buf.subarray(0, n)));
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这不一定会读取(整)一行。例如,当标准输入从文件重定向时,它将读取一大块而不仅仅是一行。如果该行很长,则读取的内容会少于整行。此外,它可能不一定读取整个 utf-8 符文,因此它可能会破坏文本编码。 (2认同)

ADI*_*MAR 6

我们可以在 deno 中使用 prompt。

const input = prompt('Please enter input');
Run Code Online (Sandbox Code Playgroud)

如果输入必须是数字。我们可以使用Number.parseInt(input);


Rot*_*eti 5

一个简单的确认,可以用y或回答n

import { readLines } from "https://deno.land/std@0.76.0/io/bufio.ts";

async function confirm(question) {
    console.log(question);

    for await (const line of readLines(Deno.stdin)) {
        if (line === "y") {
            return true;
        } else if (line === "n") {
            return false;
        }
    }
}

const answer = await confirm("Do you want to go on? [y/n]");
Run Code Online (Sandbox Code Playgroud)

或者,如果您想提示用户输入字符串

import { readLines } from "https://deno.land/std@0.76.0/io/bufio.ts";

async function promptString(question) {
    console.log(question);

    for await (const line of readLines(Deno.stdin)) {
        return line;
    }
}

const userName = await promptString("Enter your name:");
Run Code Online (Sandbox Code Playgroud)

  • @phil294 它使用的是“std”的“0.51.0”,该版本已被弃用。在答案中修改了版本,它现在应该可以工作了。 (2认同)