Skip to content

Instantly share code, notes, and snippets.

@akras14
Created April 25, 2014 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akras14/11298244 to your computer and use it in GitHub Desktop.
Save akras14/11298244 to your computer and use it in GitHub Desktop.
Get user input and output from command line in NodeJs http://st-on-it.blogspot.com/2011/05/how-to-read-user-input-with-nodejs.html
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);
}
});
}
ask("Name", /.+/, function(name) {
ask("Email", /^.+@.+$/, function(email) {
console.log("Your name is: ", name);
console.log("Your email is:", email);
process.exit();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment