Program must get 2 variables. For example it must be login and password. Script can receive it from command line (login OR login with password). If no one command line arguments not filled user must enter it with stdin. If user entered only one agrument - I need ask user for second. If user entered both arguments - nothing to do (exec some func).
Question is: how correctly build program on node.js (async).
On some events or what?
I wrote this code, how I can improve this?
if(process.getuid() != 0) {
console.log('Error!');
console.log('Required root privileges');
process.exit(1);
}
var getUser = function(user, callback) {
if( user == undefined ) {
ask('Enter user', /.+/, function(user) {
callback(user, process.argv[3]);
});
} else {
callback(user, process.argv[3]);
}
}
var getPassword = function(user, password) {
if( password == undefined ) {
ask('Enter password', /.+/, function(password) {
addUser(user, password);
});
} else {
addUser(user, password);
}
}
function addUser(user, password) {
console.log('Adding user:');
console.log(user);
console.log(password);
process.exit(0);
}
var user = getUser(process.argv[2], getPassword);
function ask(question, format, callback) {
var stdin = process.stdin, stdout = process.stdout;
stdin.resume();
stdout.write(question + ": ");
stdin.once('data', function(data) {
data = data.toString().trim();
if (format.test(data)) {
callback(data);
} else {
stdout.write("It should match: "+ format +"\n");
ask(question, format, callback);
}
});
}