Skip to content

Instantly share code, notes, and snippets.

@AtulKhanduri
Last active November 23, 2017 19:27
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 AtulKhanduri/04b911f47a912f15fbac49128760416a to your computer and use it in GitHub Desktop.
Save AtulKhanduri/04b911f47a912f15fbac49128760416a to your computer and use it in GitHub Desktop.
Read Standard Input from console in JS using Await, Async & Promise
// Option 1: Using ReadLine
async function read_stdin_using_readline () {
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
return new Promise(function(resolve) {
// rl.on('line', function(param){
// console.log(param);
// resolve(param)
// });
rl.question('Provide input? ', function(answer) {
rl.close();
resolve(answer);
});
});
}
// Option 2: Using process.stdin
async function read_stdin_using_stdin(){
return new Promise(function(resolve) {
// process.stdin.on('readable', () => {
process.stdin.on("data", function (chunk) {
// const chunk = process.stdin.read();
if (chunk !== null) {
//Stop reading input
process.stdin.pause();
// resolve => process.stdout.write(`data: ${chunk}`);
resolve(chunk.toString());
}
});
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment