readline processes input before it is provided

53 views Asked by At

I'm trying to make a program that takes 2 emails separated by a comma as input and sends one email each to them. I'm using the readline module for taking input and the nodemailer module for sending the mails.

Code:

const readline = require('readline')
let rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question('enter emails seperated by a comma: ', (ans) => {
    var players = ans.split(',');
    mailOptions1.to = players[0];
    mailOptions2.to = players[1];
    nextFunction();
}

here nextFunction is a function that generates the text of the email and sends it.

When I execute this code the question 'enter emails separated by a comma: ' shows and as I'm entering the emails, it suddenly tries to send the mail and gives a no recipients defined error (obviously, since I'm in the process of defining the recipients)

Any insight on why this is happening and how it can be fixed will be much appreciated. :)

UPDATE: As Jeff pointed out, the logic behind the code is fine. It seems there is some other part of my application that is giving rise to the error. This question was perhaps irrelevant. :/

1

There are 1 answers

1
Jeff Kilbride On BEST ANSWER

I tested this and it worked for me. I put the following in rl-test.js:

const readline = require('readline');
let rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question('enter emails separated by a comma: ', (ans) => {
    var players = ans.split(',');
    console.log(players[0] + '\n' + players[1]);
});

and invoked it from the command line with node rl-test.js with the following results:

$ node rl-test.js
enter emails seperated by a comma: foo,bar
foo
bar

Not sure what to tell you, but wanted you to know that it does work. Can you try this?