'Readline filtering answers
I want to filter answers in the built-in module in nodejs called "readline" which allows you to prompt a user and ask some question, yk things like that, I've made a js file for my users to easily understand what to do on my discord bot. Installing dependencies, git pull, ye it explains it. But I want it to only accept certain answers. Here is the code for you to understand it
const readline = require("readline")
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
console.log("Hello! Welcome to the startup file of my bot dio! You can use this file to easily install,uninstall and update files!")
console.log('Type npm install if you want to install the needed packages. ')
console.log('Type git pull to update the whole folder but it needs a token and username so ye just enter it.')
console.log('Type node index.js of you want to start the bot')
rl.question('Now, what do you want to do? ', (answer) => {
const { execSync } = require('child_process')
const start = () => {
execSync(`${answer}`, { stdio: "inherit" });
}
start();
rl.close();
});
I want this code to only accept the given answers I provided (npm install, git pull, node index.js)
Solution 1:[1]
I finally got it! I just used if arrays lol ?. I completely forgot about it. Here's the code
const readline = require("readline")
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const answers = ['npm install', 'git pull', 'node index.js']
console.log("Hello! Welcome to the startup file of my bot dio! You can use this file to easily install,uninstall and update files!")
console.log('Type npm install if you want to install the needed packages. ')
console.log('Type git pull to update the whole folder but it needs a token and username so ye just enter it.')
console.log('Type node index.js of you want to start the bot')
rl.question('What do you want to do? ', (answer) => {
const { execSync } = require('child_process');
if(answer === answers[0]){
console.log('Installing packages...')
execSync('npm install', {stdio: 'inherit'})
console.log('Installed!')
}
else if(answer === answers[1]){
console.log('Updating...')
execSync('git pull', {stdio: 'inherit'})
console.log('Updated!')
}
else if(answer === answers[2]){
console.log('Starting...')
execSync('node index.js', {stdio: 'inherit'})
console.log('Started!')
}
else{
rl.setPrompt('Wrong input! Try again!')
rl.prompt()
}
rl.close();
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rain Andrew Bacor |
