我使用node
作为JavaScript REPL。是否可以使用prompt
,如下例所示?
function foo() {
var i = prompt("enter value for i: ");
console.log('i is now: '+i);
}
foo();
当我运行上面的代码(从文件j.js
加载)时,我得到:
$ node
> .load j.js
> function foo() {
... var i = prompt("enter value for i: ");
... console.log('i is now: '+i);
... }
undefined
>
undefined
> foo();
ReferenceError: prompt is not defined
at foo (repl:2:9)
at repl:1:1
at REPLServer.self.eval (repl.js:110:21)
at repl.js:249:20
at REPLServer.self.eval (repl.js:122:7)
at Interface.<anonymous> (repl.js:239:12)
at Interface.emit (events.js:95:17)
at Interface._onLine (readline.js:203:10)
at Interface._line (readline.js:532:8)
at Interface._ttyWrite (readline.js:815:20)
...未能解决上述问题,是否可以使用其他一些工具(基于控制台,而不是基于浏览器)作为JavaScript REPL?
答案 0 :(得分:1)
因此,您可以从正在运行的脚本中读取stdio,这是从控制台执行此操作的主要方法。有许多模块可以让事物互动,但直接节点的核心方式是使用readline:
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("What do you think of node.js? ", function(answer) {
// TODO: Log the answer in a database
console.log("Thank you for your valuable feedback:", answer);
rl.close();
});
答案 1 :(得分:-1)
提示是一种声明,您将其用作对象。而不是这样做:
var i = prompt("enter value for i: ");
你应该这样做:
prompt("enter value for i: ");