在child_process.exec的循环中以未定义形式返回的数组字符串

时间:2019-02-08 00:29:51

标签: javascript node.js

我正在创建一个有助于快速设置项目的程序。它向用户查询名称和所需的依赖项,然后创建一个文件夹并在其中安装依赖项。依赖关系存储在可以无问题访问的数组中。但是,在child_process.exec函数的循环中,数组元素以未定义的形式返回。这是代码:

const inquirer = require('inquirer');
const fse = require('fs-extra');
const cp = require("child_process");
const path = require('path');

(function(){
    let projectName;
    let dependencies;
    console.log("Welcome to Node Project Creator.");
    inquirer.prompt([{type: String, name: "ProjectName", message: "What would you like to name your project?"}]).then(function(answer){
        projectName = answer.ProjectName;
        console.log(projectName + " is a great name!");
        fse.mkdir(path.join(__dirname, projectName));
        console.log("Project folder created.");
        inquirer.prompt([{type: String, name: "dependencies", message: "Enter dependencies seperated by spaces."}]).then(function(answer){
            if (answer.dependencies){
                dependencies = answer.dependencies.split(" ");
                console.log("Okay, I will install your dependencies.");
                console.log(dependencies);
            } else {
                console.log("I guess you don't need any dependencies.");
            }
            try {
                process.chdir(path.join(__dirname, projectName));
                for (var i = 0; i < dependencies.length; i++){
                    cp.exec("npm install " + dependencies[i], function(err){
                        if (err){
                            console.error(err);
                        } else {
                           console.log(dependencies[i] + " installed.");
                        }
                    });
                    console.log("Thank you for using Node Project Creator.");
                }
            } catch (err){
                console.error(err);
            }
        });
    });
})();


1 个答案:

答案 0 :(得分:1)

cp.exec()尚未i时,异步调用您的< dependencies.length回调。尝试使用let i = 0使i绑定到每个循环值。

请参见http://exploringjs.com/es6/ch_variables.html#sec_let-const-loop-heads