Last active
November 23, 2017 19:27
-
-
Save AtulKhanduri/04b911f47a912f15fbac49128760416a to your computer and use it in GitHub Desktop.
Read Standard Input from console in JS using Await, Async & Promise
This file contains hidden or 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
// 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