I'm trying to write a script that asks three questions in a row, while waiting for user input in between each question.
It seems that I have difficulty understanding how to do this with the non-blocking nature of node.
Here's the code I'm running:
var shell = require('shelljs/global'),
utils = require('./utils'),
readline = require('readline'),
fs = require('fs'),
path = require('path');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
setUserDefaultSettings();
function setUserDefaultSettings() {
var defaultSettingsFile = find('DefaultSettings.json');
var defaultSettingsJSON = [
{
macro: '__new_project_path__',
question: 'Please enter the destination path of your new project: '
},
{
macro: '__as_classes_path__',
question: 'Please enter the path to your ActionScript Classes: ',
},
{
macro: '__default_browser_path__',
question: 'Please enter the path to your default browser: '
}
];
var settingsKeys = [];
var index = 0;
if (!test('-f', 'UserSettings.json')) {
cp(defaultSettingsFile, 'UserSettings.json');
}
var userSettingsFile = pwd() + path.sep + find('UserSettings.json');
fs.readFile(userSettingsFile, 'utf8', function (err, data) {
if (err) {
echo('Error: ' + err);
return;
}
data = JSON.parse(data);
for(var attributename in data) {
settingsKeys.push(attributename);
}
defaultSettingsJSON.forEach(function(key) {
index++;
// Check if macros have been replaced
if (data[settingsKeys[index - 1]] === key.macro) {
// Replace macros with user input.
replaceSettingMacro(userSettingsFile, key.macro, key.question);
}
});
});
}
function replaceSettingMacro(jsonFile, strFind, question) {
askUserInput(question, function(strReplace) {
sed('-i', strFind, strReplace, jsonFile);
});
}
function askUserInput(string, callback) {
rl.question(string, function(answer) {
fs.exists(answer, function(exists) {
if (exists === false) {
echo('File ' + answer + ' not found!');
askUserInput(string, callback);
} else {
callback(answer);
}
});
});
}
Only the first question is asked, as the script continues execution while the user is inputting their answer. I understand why this is the case, but don't know how I can work around this.