Node.js中使用回调函数获取用户输入报错求助
Node.js回调函数合并代码报错解决求助
我参考了Node.js中使用回调函数获取用户输入的相关教程,尝试将两段代码合并后运行,控制台抛出错误。预期能输出类似hello *的内容,但不知如何解决,特此求助。
我尝试的代码
const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout }); let greetings = (name) => { window.alert(`hello ${name}`); } let processUserInput = (callback) => { readline.question("Who are you? ", input => { callback(input); readline.close(); }); } processUserInput(greetings);
参考的两段代码
第一段:
const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout }); readline.question('Who are you?', name => { console.log(`Hey there ${name}!`); readline.close(); });
第二段:
function greeting(name) { alert(`Hello, ${name}`); } function processUserInput(callback) { const name = prompt("Please enter your name."); callback(name); } processUserInput(greeting);
控制台报错信息
node:internal/readline/emitKeypressEvents:74 throw err; ^ ReferenceError: window is not defined at greetings (/Users/*/Documents/vscode/09/temp.js:7:5) at /Users/*/Documents/vscode/09/temp.js:12:9 at [_onLine] [as _onLine] (node:internal/readline/interface:421:7) at [_line] [as _line] (node:internal/readline/interface:894:18) at [_ttyWrite] [as _ttyWrite] (node:internal/readline/interface:1272:22) at ReadStream.onkeypress (node:internal/readline/interface:271:20) at ReadStream.emit (node:events:512:28) at emitKeys (node:internal/readline/utils:357:14) at emitKeys.next (<anonymous>) at ReadStream.onData (node:internal/readline/emitKeypressEvents:64:36)
问题原因及解决方法
错误原因很明确:window是浏览器环境特有的全局对象,Node.js运行环境中不存在window对象,所以调用window.alert会抛出ReferenceError。
你参考的第二段代码是浏览器环境下的写法(用alert和prompt),而第一段是Node.js环境的写法(用readline和console.log),合并时混淆了两个环境的API。
修正方法:将window.alert替换为Node.js中用于控制台输出的console.log,修改后的代码如下:
const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout }); let greetings = (name) => { console.log(`hello ${name}`); // 替换window.alert为console.log } let processUserInput = (callback) => { readline.question("Who are you? ", input => { callback(input); readline.close(); }); } processUserInput(greetings);
运行这段代码后,输入名字就能得到预期的hello [你的名字]输出。
内容的提问来源于stack exchange,提问作者Mccranky83
相关产品推荐
相关产品推荐

