I'm creating a program that helps to quickly set up projects. It queries the user for a name and the dependencies needed, then creates a folder and should install the dependencies in it. Dependencies are stored in an array that can be accessed without issue. However, within the loop in the child_process.exec function, the array elements come back as undefined. Here's the code:
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);
}
});
});
})();