You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node终端使用prompt-sync输入时重复显示提示文本的问题求助

问题解决:Node.js中prompt-sync输入时重复显示提示文本

问题描述

我创建了存储商品(apple、mango等)价格信息的对象,通过prompt与if/else实现两种功能:在浏览器中,输入商品名可显示对应价格,按P键可显示最高价与最低价,功能正常。但在Node终端中使用prompt-sync模块时,输入任意字符都会重复显示提示文本,仅输入完整内容后才能正常返回结果。

原代码

const salad = {
  apple: 1,
  orange: 2,
  banana: 0.8,
  mango: 1.6,
};

const prompt = require('prompt-sync')({ sigint: true });

const interestedIn = prompt(
  `Do you want to know the price? Choose: apple, orange, banana, mango.
If you want to know the highest and the lowest price of products in the list, press P.`
);

if (salad[interestedIn]) {
  console.log(`The price of this product is ${salad[interestedIn]} €.`);
} else {
  console.log(
    `The most expensive product is ${salad.orange} euros and the most expensive is ${salad.banana} euros. `
  );
}

解决方案

1. 解决输入重复提示的核心问题

问题根源是prompt-sync的prompt函数会在输入过程中重复渲染传入的多行提示文本。解决方法是先单独打印提示内容,再调用prompt仅显示简洁的输入提示符:

// 先打印提示文本,避免输入时重复渲染
console.log(`Do you want to know the price? Choose: apple, orange, banana, mango.
If you want to know the highest and the lowest price of products in the list, press P.`);
// 仅用简洁提示符接收输入
const interestedIn = prompt('> ');

2. 修复逻辑与文案错误

原代码还存在两处明显问题:

  • 输入不存在的商品名或小写p时会直接进入else分支,逻辑覆盖不全;
  • else分支文案错误,将最低价描述成了最高价。

优化后的完整代码:

const salad = {
  apple: 1,
  orange: 2,
  banana: 0.8,
  mango: 1.6,
};

const prompt = require('prompt-sync')({ sigint: true });

console.log(`Do you want to know the price? Choose: apple, orange, banana, mango.
If you want to know the highest and the lowest price of products in the list, press P or p.`);
const interestedIn = prompt('> ').trim();

// 优先判断高低价指令(支持大小写)
if (interestedIn.toLowerCase() === 'p') {
  const prices = Object.values(salad);
  const highestPrice = Math.max(...prices);
  const lowestPrice = Math.min(...prices);
  console.log(`The most expensive product costs ${highestPrice} euros, the cheapest costs ${lowestPrice} euros.`);
} else if (salad.hasOwnProperty(interestedIn)) {
  // 判断商品名是否存在
  console.log(`The price of ${interestedIn} is ${salad[interestedIn]} €.`);
} else {
  // 处理无效输入
  console.log('Invalid input! Please enter a valid product name or press P/p for price range.');
}

优化说明

  • 拆分提示打印与输入接收,彻底解决重复显示问题;
  • 支持大小写P指令,提升用户容错性;
  • 动态计算高低价,无需硬编码,后续商品更新无需修改逻辑;
  • 增加输入内容去空格处理,避免用户误输入空格导致的识别失败;
  • 补充无效输入提示,完善交互逻辑。

内容的提问来源于stack exchange,提问作者Node.jsMaster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 10:21:38