Skip to content

Instantly share code, notes, and snippets.

@unes
Created August 25, 2023 18:16
Show Gist options
  • Save unes/a11cfbdbbc78225581ab57cd1d896146 to your computer and use it in GitHub Desktop.
Save unes/a11cfbdbbc78225581ab57cd1d896146 to your computer and use it in GitHub Desktop.
Using nodeJS readline module, adding contacts
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const contacts = [];
function addContact() {
rl.question('Enter name: ', (name) => {
rl.question('Enter phone #: ', (phoneNumber) => {
contacts.push({ name, phoneNumber });
console.log('Contact added successfully!\n');
showMenu();
});
});
}
function viewContacts() {
if (contacts.length === 0) {
console.log('No contacts available.\n');
} else {
console.log('Contacts:');
contacts.forEach((contact, index) => {
console.log(`${index + 1}. Name: ${contact.name}, Phone: ${contact.phoneNumber}`);
});
console.log('');
}
showMenu();
}
function showMenu() {
console.log('Choose an option:');
console.log('a : to add a contact');
console.log('v : to View all contacts');
rl.question('Enter your choice: ', (choice) => {
switch (choice) {
case 'a':
addContact();
break;
case 'v':
viewContacts();
break;
default:
console.log('Invalid choice. Enter v or a');
showMenu();
break;
}
});
}
showMenu();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment