Wednesday, 26 April 2017

How to get synchronous "readline" function in nodejs?

I am wondering if there is a simple way to get "synchronous" readline or at least get the appearance of synchronous I/O in node.js

I use something like this but it is quite awkward

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

var i = 0;
var s1 = '';
var s2 = '';

rl.on('line', function(line){
    if(i==0) { s1 = line; }
    else if(i==1) { s2 = line; }
    i++;
})

rl.on('close', function() {
    //do something with lines
})'

I would also prefer to not just read entire stdin and then separate out the lines manually after-the-fact too. It would be great if it were as easy as

var s1 = getline();
var s2 = getline();

I can't use external modules like readline-sync because I am using a code submission website. If it uses async/await or generators that might be fine though



via Colin D

No comments:

Post a Comment