I want to create a nodejs cli app, where there is a shell.
I have tried doing this so far:
JavaScript
x
5
1
readline.question('> ', val => {
2
console.log(val)
3
readline.close();
4
});
5
But it only works once, how do I make it work continuously?
Like so:
JavaScript
1
5
1
> Hello
2
Hello
3
> World
4
World
5
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:
JavaScript
1
11
11
1
function askQuestion(){
2
readline.question('> ', val => {
3
4
console.log(val);
5
askQuestion() // ask next question
6
});
7
}
8
9
askQuestion() // initialize question terminal
10
11
If you also need a command to exit out of question loop, you can even add a breaking condition like this
JavaScript
1
15
15
1
function askQuestion(){
2
readline.question('> ', val => {
3
if(val==='exit'){ //breaking condition
4
5
readline.close()
6
return;
7
}
8
console.log(val);
9
askQuestion() // ask next question
10
});
11
}
12
13
askQuestion() // initialize question terminal
14
15