I want to create a nodejs cli app, where there is a shell.
I have tried doing this so far:
readline.question('> ', val => {
console.log(val)
readline.close();
});
But it only works once, how do I make it work continuously?
Like so:
> Hello Hello > World World
Advertisement
Answer
That is happening because you are only calling the question function once. To ask for next input you need to call it again inside the callback. I would create a recursive function like this:
function askQuestion(){
readline.question('> ', val => {
console.log(val);
askQuestion() // ask next question
});
}
askQuestion() // initialize question terminal
If you also need a command to exit out of question loop, you can even add a breaking condition like this
function askQuestion(){
readline.question('> ', val => {
if(val==='exit'){ //breaking condition
readline.close()
return;
}
console.log(val);
askQuestion() // ask next question
});
}
askQuestion() // initialize question terminal