如何使用Cheerio为每个匹配元素依次调用inquirer.prompt?
问题分析与解决
核心问题
你的代码存在三个关键问题导致无法正确为每个元素单独赋值:
- Cheerio的
.each()不支持异步串行执行:.each()会立即遍历所有元素,不会等待每个异步回调完成,导致所有输入操作同时触发,顺序混乱。 nameVariable未正确返回输入值:函数里虽然在then中返回了用户输入,但没有将这个结果作为函数的返回值,调用后得到的是undefined。- 未将输入值赋值给元素:代码仅调用了输入函数,但没有把用户输入的新值设置到对应的Cheerio元素上。
修复后的代码
const fs = require('fs'); const cheerio = require('cheerio'); const inquirer = require('inquirer'); async function readFile(htmlPath) { const htmlFile = fs.readFileSync(htmlPath, 'utf8'); const $ = cheerio.load(htmlFile); const dynamicElements = $('body .dynamic'); // 简化选择器 // 改用for循环实现串行异步处理 for (let i = 0; i < dynamicElements.length; i++) { const el = dynamicElements[i]; const originalValue = $(el).text().trim(); // 获取用户输入的新值 const newValue = await nameVariable(originalValue); // 将新值赋值给当前元素 $(el).text(newValue); } return $.html(); } async function nameVariable(value) { // 直接返回prompt的结果,无需then链式调用 const response = await inquirer.prompt({ type: "input", name: "variableName", message: `Name the variable for value:${value} =>`, default: "variableName", }); return response.variableName; } // 示例调用(可根据你的需求调整) // readFile('./example.html').then(newHtml => { // fs.writeFileSync('./modified.html', newHtml); // console.log('HTML文件已更新'); // });
关键改动说明
- 替换
.each()为for循环:for循环可以配合await实现逐个处理元素,确保上一个输入完成后再处理下一个,避免异步操作混乱。 - 修复
nameVariable的返回值:直接返回inquirer.prompt()的结果,确保调用函数能获取到用户输入的新值。 - 添加元素赋值逻辑:调用
$(el).text(newValue)将用户输入的内容设置到对应的元素中,这是实现修改的核心步骤。
内容的提问来源于stack exchange,提问作者Jabli
相关产品推荐
相关产品推荐

