Inquirer包输出重复异常问题排查求助
问题分析与解决
问题原因
- 异步函数未正确等待:
setup是异步函数,但在handler中调用时未添加await,导致后续的createFile、console.log("Done")会和setup内部的Inquirer交互同时执行,终端输出被打乱,出现重复现象。 - stdio状态干扰:使用
execSync('npm init', {stdio: 'inherit'})会直接继承当前进程的stdio,执行完成后可能未正确恢复终端状态,影响后续Inquirer的输出渲染。
解决方案
1. 等待异步函数执行完成
在handler中调用setup(jsonFile)时添加await,确保setup内所有操作完成后再执行后续代码:
// 替换原代码中的 setup(jsonFile); await setup(jsonFile);
2. 统一使用execa处理npm init(避免execSync干扰)
把execSync的调用替换为execa的异步调用,保持stdio的一致性:
// 替换原else块中的代码 else { await execa("npm init", { stdio: "inherit" }); }
3. 优化Inquirer调用逻辑(可选)
将Inquirer的then/catch改为async/await写法,让代码更清晰:
// 替换原Inquirer调用部分 try { const answers = await inquirer.prompt(questions); console.log(chalk.green(`The package ${answers.option} will be downloaded`)); } catch(err) { console.log("There was an error"); }
修改后的完整handler代码片段
handler: async (argv) => { let packages = []; let dependencies = ''; const execa = util.promisify(exec); async function setup(jsonFile) { // no libraries are given, add default librariesthen create the file if (argv._.length == 1) { console.log(chalk.yellow("Note: Predefined libraries will be added to the package.json")); console.log(chalk.yellow("Please select the database you'd like to connect to your application: ")); try { const answers = await inquirer.prompt(questions); console.log(chalk.green(`The package ${answers.option} will be downloaded`)); } catch(err) { console.log("There was an error"); } packages.push("express", "ejs", "dotenv", "cors", "body-parser"); dependencies = await installPackages(packages); renderTemplate("./bin/templates/_index.ejs", "./", jsonFile.main || "index.js", {path: "/public/index.html"}); } else if(argv._.length > 1) { //get all the arguments after the first ('create-node-app') argument to get all packages packages = argv._.slice(1); dependencies = await installPackages(packages); createFile("./", jsonFile.main || "index.js", "//This is the server file"); } createFolder("./", "public", rl); renderTemplate("./bin/templates/_indexhtml.ejs", "./public/", "index.html", jsonFile); renderTemplate("./bin/templates/_styles.ejs", "./public/", "styles.css", ""); renderTemplate("./bin/templates/_app.ejs", "./public/", "app.js", ""); } //if the y flag is used let jsonFile; if(argv.y) { await execa("npm init -y"); } else { await execa("npm init", { stdio: "inherit" }); } console.log("The package.json file has been created"); jsonFile = JSON.parse(fs.readFileSync("./package.json")); await setup(jsonFile); // 添加await createFile("./", ".env", ""); createFile("./", ".gitignore", "node_modules\n.env"); console.log("Done"); }
内容的提问来源于stack exchange,提问作者Viraj Doshi
相关产品推荐
相关产品推荐

