如何在 javascript 中获取控制台输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3120761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:20:09  来源:igfitidea点击:

How do I get console input in javascript?

javascriptinputconsolespidermonkey

提问by camel_space

I'm currently using spidermonkey to run my JavaScript code. I'm wondering if there's a function to get input from the console similar to how Python does this:

我目前正在使用蜘蛛猴来运行我的 JavaScript 代码。我想知道是否有一个函数可以从控制台获取输入,类似于 Python 的执行方式:

var = raw_input()  

Or in C++:

或者在 C++ 中:

std::cin >> var;

I've looked around and all I've found so far is how to get input from the browser using the prompt() and confirm() functions.

我环顾四周,到目前为止我发现的只是如何使用 prompt() 和 confirm() 函数从浏览器获取输入。

回答by Zaz

In plain JavaScript, simply use response = readline()after printing a prompt.

在纯 JavaScript 中,只需response = readline()在打印提示后使用即可。

In Node.js, you'll need to use the readline module: const readline = require('readline')

在 Node.js 中,您需要使用readline 模块const readline = require('readline')

回答by Keyvan

As you mentioned, promptworks for browsers all the way back to IE:

正如您所提到的,prompt适用于一直回到 IE 的浏览器:

var answer = prompt('question', 'defaultAnswer');

prompt in IE

IE 中的提示

For Node.js > v7.6, you can use console-read-write, which is a wrapper around the low-level readlinemodule:

对于 Node.js > v7.6,您可以使用console-read-write,它是低级readline模块的包装器:

const io = require('console-read-write');

async function main() {
  // Simple readline scenario
  io.write('I will echo whatever you write!');
  io.write(await io.read());

  // Simple question scenario
  io.write(`hello ${await io.ask('Who are you?')}!`);

  // Since you are not blocking the IO, you can go wild with while loops!
  let saidHi = false;
  while (!saidHi) {
    io.write('Say hi or I will repeat...');
    saidHi = await io.read() === 'hi';
  }

  io.write('Thanks! Now you may leave.');
}

main();
// I will echo whatever you write!
// > ok
// ok
// Who are you? someone
// hello someone!
// Say hi or I will repeat...
// > no
// Say hi or I will repeat...
// > ok
// Say hi or I will repeat...
// > hi
// Thanks! Now you may leave.

DisclosureI'm author and maintainer of console-read-write

披露我是控制台读写的作者和维护者

For SpiderMonkey, simple readlineas suggested by @MooGooand @Zaz.

对于 SpiderMonkey,readline就像@MooGoo@Zaz建议的那样简单。