Node.js应用仅运行单个函数即终止的原因及连续执行解决方案
问题分析与修复方案
你的代码存在三个关键问题,导致应用提前终止且第二个提示无法正常触发:
- 语法错误:第二个
io.question的括号位置错误,你把回调函数写在了括号外面,导致这个回调没有被绑定到提问操作上,而且第二个提问会在第一个提问还没得到响应时就执行,逻辑顺序完全混乱。 - 闰年判断逻辑缺失输出:当年份是整百年但不能被400整除时,你的代码只返回了
false,没有打印对应的提示信息,用户看不到这个情况的结果。 - 函数调用错误:
response.toLowerCase是函数引用,需要加括号调用response.toLowerCase()才能得到转换后的字符串,否则永远不会等于'y'。
修复后的完整代码
const readline = require('readline'); const io = readline.createInterface({ input: process.stdin, output: process.stdout }); console.log( 'Welcome. This application will check if a given year is a leap year.' ); checkYear(); function checkYear() { io.question('Check which year? ', function (year) { // 修复闰年判断的输出逻辑 if (year % 100 === 0 && year % 400 !== 0) { console.log(year + ' is not a leap year.'); } else if (year % 4 === 0) { console.log(year + ' is a leap year.'); } else { console.log(year + ' is not a leap year.'); } // 修复第二个question的语法,将回调放在括号内,且在第一个提问的回调里触发 io.question('Check another year? y/n ', function(response) { // 修复toLowerCase的调用方式 if (response.toLowerCase() === 'y') { checkYear(); } else { io.close(); } }); }); };
核心修复点说明
- 将第二个
io.question移到第一个提问的回调函数内部,确保它在用户回答完年份后才触发。 - 修正第二个
io.question的括号位置,把回调函数作为第二个参数传入。 - 补全年份是整百年但非400倍数时的输出语句,让所有情况都有明确提示。
- 把
response.toLowerCase改为response.toLowerCase(),正确调用字符串转小写的方法。
内容的提问来源于stack exchange,提问作者surfturkey
相关产品推荐
相关产品推荐

