简体   繁体   English

如何在Node.js REPL上使用`prompt`

[英]how to use `prompt` on Node.js REPL

I am using node as a JavaScript REPL. 我正在使用node作为JavaScript REPL。 Is it possible to use prompt as in the example below? 是否可以使用下面的示例中的prompt

function foo() {
    var i = prompt("enter value for i: ");
    console.log('i is now: '+i);
}

foo();

When I run the above code (loading it from file j.js ), I get: 当我运行以上代码(从文件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)

... failing a solution to the above problem, is that some other tool (console-based, not browser-based) I can use as a JavaScript REPL? ...无法解决上述问题,是否可以将其他某些工具(基于控制台而不是基于浏览器)用作JavaScript REPL?

So you can read stdio from the script you're running, which is the main way to do it from the console. 因此,您可以从正在运行的脚本中读取stdio,这是从控制台执行此操作的主要方法。 There's a number of modules for making things interactive, but the straight node core way to do it is with readline: 有许多用于使事物交互的模块,但是直接节点的核心方法是使用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();
});

Prompt is a statement and you're using it as an object. 提示是一条语句,您正在将其用作对象。 Instead of doing this: 而不是这样做:

    var i = prompt("enter value for i: ");

You should do this: 你应该做这个:

     prompt("enter value for i: ");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM