gpt4 book ai didi

javascript - Node js readline不断评估输入并返回错误

转载 作者:行者123 更新时间:2023-11-30 21:08:14 24 4
gpt4 key购买 nike

在 Linux 终端上运行 Node 时,我遇到了来自 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 不应该完全避免这种情况吗?也许我犯了一些简单的错误,如果是这样请帮我找到它。提前谢谢你。

最佳答案

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

问题是您正在尝试在 REPL 中运行这段代码,而当您输入 Daniel 时在下一行 Node 中尝试查找名称为 Daniel 的变量.

关于javascript - Node js readline不断评估输入并返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46410558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com