Last active
October 30, 2016 15:38
-
-
Save mnyamor/4f0d773a298bc4e2becc94d3ac782bf6 to your computer and use it in GitHub Desktop.
Collecting information with Readline
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*Readline is a module that allows us to ask questions to our Terminal user. | |
The standard input(stdin) and standard output(stdout) objects that allow | |
us to easily control prompting a user with questions and saving those answers. | |
*/ | |
//create an instance of the readline object which will create the propmt. | |
var readline = require('readline'); | |
var realPerson = { | |
name: '', | |
saying: [] | |
}; | |
//use readline to create the interface that takes in process.stdin & process.stdou | |
var rl = readline.createInterface(process.stdin, process.stdout); | |
// use that answer to set the real person's name | |
realPerson.name = answer; | |
//in order to ask the question, we need to invoke rl.question | |
rl.question('What is the name of a real person', function(answer) { | |
// function that we can use to set the Readline prompt | |
rl.setPrompt(`What would ${realPerson.name} say? ('exit' to leave)` ); | |
rl.prompt(); | |
/*rl.on('line') is an event that will fire when the user submits an answer | |
This callback function, the second argument of the rl.on('line', function() will also be invoked once we have that answer | |
*/ | |
rl.on('line', function(saying) { | |
if( saying.toLowercase.trim() === 'exit') { | |
rl.close(); | |
} else { | |
rl.setPrompt(`What else would ${realPerson.name} say? ('exit' to leave) `) | |
} | |
console.log(saying.trim()); | |
}); | |
}); | |
//rl.on('close') will listen for a close event. | |
rl.on('close', function() { | |
/*a %s in the console log is a placeholder for a string | |
So what it will do is it will replace the second argument that we have added with that string. | |
a %j in the console log will replace it variable with a JSON String. | |
*/ | |
console.log('%s is a real persons that says %j', realPerson.name, realPerson.sayings); | |
//invoke a process.exit to end the proces | |
process.exit(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment