FAQ Chatbot Node.js
👤 Sharing: AI
```javascript
// Import necessary modules
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
});
// Define the FAQ data (question-answer pairs)
const faqData = {
"What is your name?": "I am a simple FAQ chatbot.",
"How do you work?": "I use a simple lookup to find answers to your questions.",
"What can you do?": "I can answer frequently asked questions.",
"Are you a real person?": "No, I am a computer program.",
"What is Node.js?": "Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine.",
"How to install Node.js?": "You can download the latest version from the official Node.js website: https://nodejs.org/",
"What are npm packages?": "npm packages are reusable modules or libraries that can be used to extend the functionality of your Node.js projects.",
"How to create a Node.js project?": "Use `npm init` command to initialize a new Node.js project.",
"What is Express.js?": "Express.js is a popular web application framework for Node.js.",
"How to install express?": "Use `npm install express` to install express package."
// Add more questions and answers here
};
// Function to handle user input and provide answers
function askQuestion() {
readline.question('Ask your question (or type "exit" to quit): ', (question) => {
if (question.toLowerCase() === 'exit') {
console.log('Goodbye!');
readline.close();
return;
}
// Look up the answer in the FAQ data
const answer = faqData[question];
if (answer) {
console.log('Answer:', answer);
} else {
console.log('Sorry, I don\'t have an answer to that question.');
}
// Ask the next question
askQuestion();
});
}
// Start the chatbot
console.log('Welcome to the FAQ Chatbot!');
askQuestion();
/*
Explanation:
1. **Import `readline`:**
- `const readline = require('readline').createInterface(...)` imports the `readline` module, which allows us to read input from the console (standard input) and write output to the console (standard output).
- `createInterface` creates an interface to handle the input and output streams.
2. **Define FAQ Data (`faqData`):**
- `const faqData = { ... }` defines an object that stores the frequently asked questions and their corresponding answers. It's a simple key-value store (dictionary or hash map).
- Keys are the questions, and values are the answers. You should expand this object with more relevant FAQs for your use case.
3. **`askQuestion()` Function:**
- This function is the core of the chatbot's interaction loop.
- `readline.question(...)` displays a prompt to the user and waits for them to enter input. The input is passed as the `question` argument to the callback function.
- **Exit Condition:** `if (question.toLowerCase() === 'exit')` checks if the user entered "exit" (case-insensitive). If so, it prints a goodbye message, closes the `readline` interface, and exits the function, terminating the program.
- **Lookup Answer:** `const answer = faqData[question]` attempts to find the answer to the user's question by using the question as a key in the `faqData` object. If the question exists as a key, the corresponding value (the answer) is assigned to the `answer` variable.
- **Provide Answer or "Not Found":**
- `if (answer)` checks if an answer was found (i.e., if `answer` is not `undefined`).
- If an answer was found, it's printed to the console.
- If no answer was found (the question wasn't in `faqData`), a "Sorry, I don't have an answer" message is printed.
- **Recursive Call:** `askQuestion()` calls itself recursively. This is how the chatbot continues to ask questions until the user types "exit". This maintains the conversation flow.
4. **Start the Chatbot:**
- `console.log('Welcome to the FAQ Chatbot!');` displays a welcome message.
- `askQuestion();` starts the interaction loop by calling the `askQuestion()` function for the first time.
How to Run the Code:
1. **Save:** Save the code as a `.js` file (e.g., `faq_chatbot.js`).
2. **Open Terminal:** Open a terminal or command prompt.
3. **Navigate:** Navigate to the directory where you saved the file using the `cd` command.
4. **Run:** Execute the script using Node.js: `node faq_chatbot.js`
5. **Interact:** The chatbot will start, and you can type questions and get answers. Type "exit" to quit.
Improvements and Considerations:
* **More Sophisticated Matching:** The current version does exact string matching. You could use techniques like:
* **Regular Expressions:** To handle variations in phrasing or spelling.
* **String Similarity Algorithms:** (e.g., Levenshtein distance, cosine similarity) to find the closest matching question even if the user's input isn't an exact match. Libraries like `string-similarity` or `natural` can help with this.
* **Natural Language Processing (NLP):** For more advanced question understanding, consider using an NLP library or service (e.g., Dialogflow, Rasa, or libraries like `natural` for simpler tasks). This would allow the chatbot to understand the *intent* of the question, even if it's phrased differently.
* **External Data Source:** Instead of hardcoding the FAQ data in the `faqData` object, you could load it from a file (e.g., a JSON or CSV file) or a database. This makes it easier to update and manage the FAQ content.
* **Asynchronous Operations:** If you're fetching data from a database or external API, use `async/await` or Promises to handle the asynchronous operations properly and prevent blocking the event loop.
* **Error Handling:** Add error handling (e.g., `try...catch` blocks) to gracefully handle potential errors, such as network errors or invalid data.
* **Logging:** Implement logging to track user interactions and potential issues. Libraries like `winston` or `morgan` are commonly used for logging in Node.js.
* **User Interface:** For a more user-friendly experience, consider building a web interface (using Express.js or a similar framework) or a command-line interface with better formatting.
* **Context Management:** For more complex conversations, you might need to maintain context (e.g., remember previous questions or answers). This can be done by storing user-specific data in a session or database.
*/
```
👁️ Viewed: 5
Comments