【问题标题】:Can I work interactively with the command line?我可以使用命令行交互工作吗?
【发布时间】:2022-04-02 12:51:47
【问题描述】:

作为玩笑的一部分,我正在尝试在 Deno 中制作 21 点。我不想将网络带入其中,而是使用交互式提示。我已经通过STD Library,但我似乎只能找到文件 IO。我暗暗希望prompt 能够保持与网络相似,但没有运气。

我之前在 Node 中使用 Readline 完成了此操作,示例:

export const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
//...
rl.question(`name? `, (name: string) => {
   // other code
});

应用程序已经运行后,如何在命令行中接受用户输入?

【问题讨论】:

    标签: deno


    【解决方案1】:
    import { readLines } from 'https://deno.land/std/io/buffer.ts';
    
    async function question() {
       console.log(question)
       // Listen to stdin input, once a new line is entered return
       for await(const line of readLines(Deno.stdin)) {
          return line;
       }
    }
    
    const answer = await question('Name?: ');
    console.log(answer);
    
    const answer2 = await question('Age?: ');
    console.log(answer2);
    

    【讨论】:

    • 在探索过程中,我发现我可以用 Deno.readAll(Deno.stdin) 做一些不好的事情,这是更充实的版本吗?
    • 如果您使用Deno.readAll,您将无法获得答案,直到您关闭stdin。所以在这里使用readLine 是你所需要的。您可以使用Deno.stdin.read(buf) 自己实现readLine 逻辑
    猜你喜欢
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 2011-01-23
    • 2013-07-14
    • 1970-01-01
    • 2017-07-11
    相关资源
    最近更新 更多