Getting values from Deno stdin

后端 未结 5 1111
梦毁少年i
梦毁少年i 2021-02-14 11:43

How can we get values from standard input in Deno?

I don\'t know how to use Deno.stdin.

An example would be appreciated.

5条回答
  •  南旧
    南旧 (楼主)
    2021-02-14 12:01

    I have a solution 100% pure Deno, but not intensively tested

    async function ask(question: string = '', stdin = Deno.stdin, stdout = Deno.stdout) {
      const buf = new Uint8Array(1024);
    
      // Write question to console
      await stdout.write(new TextEncoder().encode(question));
    
      // Read console's input into answer
      const n = await stdin.read(buf);
      const answer = new TextDecoder().decode(buf.subarray(0, n));
    
      return answer.trim();
    }
    
    const answer = await ask(`Tell me your name? `);
    console.log(`Your name is ${answer}`);
    

    Parts of the above code was taken from answer of Kevin Qian

提交回复
热议问题