Catalyst
Catalyst

Reputation: 328

NodeJS run program in a continuous loop

I'm developing a simplex (one way) chat application and this app needs to take a certain input and send it to a messaging queue and then at the receivers end.

The issue I'm facing is that whenever the app is run on my dev environment, it runs once and finishes execution immediately. How do I make it run in an infinite loop where it waits for the user to input certain things, runs it, and wait for the next set of input. I tried a while loop but it didn't work.

function printforme() {
    rl.question("message: ", function(answer) {
        console.log("Your message: ", answer);
        rl.close();
    });
}
printforme();

Upvotes: 0

Views: 598

Answers (1)

jfriend00
jfriend00

Reputation: 707806

You can just remove the rl.close() and call yourself again to keep asking for more input:

function printforme() {
    rl.question("message: ", function(answer) {
        console.log("Your message: ", answer);
        // check if we're supposed to exit
        if (answer === "exit") {
            rl.close()
        } else {
            // ask for input again
            printforme();
        }
    });
}
printforme();

When you call rl.close(), there is nothing left for the nodejs app to do so it exits. If you want to ask another question, then remove the rl.close() and call printforme() again from inside the rl.question() callback. Because the callback is asynchronous, this will not create stack buildup. The stack completely unwinds before the async callback is called.

Upvotes: 1

Related Questions