我目前正在使用spidermonkey来运行我的JavaScript代码。我想知道是否有一个从控制台获取输入的函数,类似于Python的工作方式:
var = raw_input()
或者在C ++中:
std::cin >> var;
我环顾四周,到目前为止我发现的是如何使用prompt()和confirm()函数从浏览器获取输入。
在纯JavaScript中,只需在打印提示后使用response = readline()
。
在Node.js中,您需要使用readline module:const readline = require('readline')
正如您所提到的,prompt
适用于浏览器一直回到IE:
var answer = prompt('question', 'defaultAnswer');
对于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的作者和维护者