49 lines
1.3 KiB
JavaScript
49 lines
1.3 KiB
JavaScript
const readline = require('readline');
|
|
|
|
function createQuestion(item, result) {
|
|
let question = item.question || item.name;
|
|
if(item.default) {
|
|
question += ` (${item.default(result)})`
|
|
}
|
|
question += ': '
|
|
return question
|
|
}
|
|
|
|
function promptQuestion(question, results) {
|
|
process.stdout.write(createQuestion(question, results))
|
|
}
|
|
|
|
module.exports.start = function(schema, cb) {
|
|
|
|
let rl = readline.createInterface({
|
|
input: process.stdin,
|
|
output: process.stdout,
|
|
terminal: true
|
|
});
|
|
|
|
let results = {};
|
|
let idx = 0;
|
|
let currentQuestion = schema[idx];
|
|
|
|
promptQuestion(currentQuestion, results);
|
|
|
|
rl.on('line', function(line){
|
|
if(currentQuestion.validator && !line.match(currentQuestion.validator)) {
|
|
console.error('Error:', currentQuestion.error || 'Invalid input!')
|
|
} else {
|
|
if(!line && currentQuestion.default) {
|
|
line = currentQuestion.default(results)
|
|
}
|
|
line = line.length && line || undefined
|
|
results[currentQuestion.name] = line;
|
|
idx++;
|
|
if(idx >= schema.length) {
|
|
rl.close();
|
|
cb(results);
|
|
return;
|
|
}
|
|
currentQuestion = schema[idx];
|
|
}
|
|
promptQuestion(currentQuestion, results);
|
|
})
|
|
}
|