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

问题描述 投票:50回答:3

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

var = raw_input()  

或者在C ++中:

std::cin >> var;

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

javascript input console spidermonkey
3个回答

12
投票

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

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


2
投票

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

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

prompt in IE

对于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.

Disclosure我是console-read-write的作者和维护者

对于SpiderMonkey,readline@MooGoo建议的简单@Zaz

© www.soinside.com 2019 - 2024. All rights reserved.