节点js readline继续评估输入并返回错误

时间:2017-09-25 17:06:05

标签: javascript node.js readline

在Linux终端上运行节点时,我正在运行Node js readline模块的奇怪行为。该模块可以工作,但它也尝试评估用户输入,就像它是一个语句,返回一个参考错误。这只是我做的一个简单的测试,但无法让它工作......我已经尝试了很多教程。继承我的代码:

'nodeReadlineTeste':function(){

var readline = require('readline');

//without terminal:false I was getting double lettering on terminal input...
var rl = readline.createInterface({input:process.stdin,output:process.stdout,terminal:false});

rl.question('What is your name? ',function(resp){getIt(resp)});

//this function is to bypass NODE assyncronous nature... I was getting the log before even answering.
function getIt (resp){console.log(resp); rl.close()};

},

//运行此方法并回复我的名字时,我得到了这个结果:

> global.nodeReadlineTeste()
What is your name? undefined
> Daniel
ReferenceError: Daniel is not defined
at repl:1:1
at ContextifyScript.Script.runInThisContext (vm.js:44:33)
at REPLServer.defaultEval (repl.js:239:29)
at bound (domain.js:301:14)
at REPLServer.runBound [as eval] (domain.js:314:12)
at REPLServer.onLine (repl.js:440:10)
at emitOne (events.js:120:20)
at REPLServer.emit (events.js:210:7)
at REPLServer.Interface._onLine (readline.js:279:10)
at REPLServer.Interface._line (readline.js:626:8)
> Daniel

不是readline应该避免那个吗?也许我做了一些简单的错误,如果有的话请帮助我找到它。提前谢谢。

1 个答案:

答案 0 :(得分:1)

您正尝试在REPL中运行此代码。 将此代码保存到单独的<your_file_name>.js并运行 node <your_file_name>.js

问题是您尝试在REPL中运行此代码,并且在下一行节点中键入Daniel时尝试查找名为Daniel的变量。