Open In App

Book Recommendation System using Node and Express.js

Last Updated : 05 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The Book Recommendation System aims to enhance the user’s reading experience by suggesting books tailored to their interests and preferences. Leveraging the power of machine learning and natural language processing, the system will analyze user inputs and recommend relevant books from a database. In this project, we will develop a Book Recommendation System using NodeJS and ExpressJS. The system will utilize the OpenAI API for natural language processing to provide personalized book recommendations based on user preferences and input.

Output Preview: Let us have a look at how the final output will look like.

1-(online-video-cuttercom)

Prerequisites:

Approach to Create Book Recommendation System:

The Book Recommendation System will include the following functionalities:

  • Input processing: Analyze user preferences and input using the OpenAI API.
  • Book recommendation: Recommend relevant books based on user input and preferences.
  • User interface: Provide a user-friendly interface to interact with the system.

Steps to Create the NodeJS App and Installing Module:

Step 1: Create a new directory for your project and navigate into it:

mkdir book-recommendation
cd book-recommendation

Step 2: Create a server using the following command.

npm init -y

Step 3: Install Dependencies:You’ll need to install Express.js and Axios for making HTTP requests:

npm install express axios dotenv

Step 4: Create a .env file, this file will contain your environment variables, including your OpenAI API key.

PORT=3000
OPENAI_API_KEY=your_openai_api_key_here

Step 5: Create Files ie. public/index.html this file will contain the HTML structure for our webpage and public/script.js this file handles the functionality of fetching user input and sending it to the server to get book recommendations using the OpenAI API. The server.js file will contain the NodeJS server code to handle requests and interact with the OpenAI API.

Project Structure:

Screenshot-2024-02-29-130058

The updated dependencies in package.json file will look like:

"dependencies": {
"axios": "^1.6.7",
"dotenv": "^16.4.5",
"express": "^4.18.2",
"openai": "^4.28.4",
}

HTML




<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8" />
    <meta name="viewport"
     content="width=device-width, initial-scale=1.0" />
    <title>Book Recommendation</title>
    <link rel="stylesheet"
          href=
</head>
 
<body>
    <div class="container">
        <br>
        <h1 class="text-center">
            Book Recommendation System
        </h1>
        <div class="form-group">
            <label for="userInput">
                Enter Your Preferences:
            </label>
            <textarea class="form-control"
             id="userInput" rows="3">
            </textarea>
        </div>
        <button type="button"
                class="btn btn-primary"
                id="recommendBtn">
            Get Book Recommendation
        </button>
        <div id="recommendation" class="mt-3">
        </div>
        <div id="loader" class="mt-3 text-center"
         style="display: none;">
            <div class="spinner-border text-primary"
                 role="status">
                <span class="sr-only">
                    Loading...
                </span>
            </div>
        </div>
    </div>
 
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="script.js" defer></script>
</body>
 
</html>


Javascript




// public/script.js
 
document.addEventListener("DOMContentLoaded", () => {
    const recommendBtn = document.getElementById("recommendBtn");
    const userInput = document.getElementById("userInput");
    const recommendationDiv = document.getElementById("recommendation");
    const loaderDiv = document.getElementById("loader");
 
    recommendBtn.addEventListener("click", async () => {
        const inputText = userInput.value.trim();
 
        if (inputText === "") {
            alert("Please enter your preferences.");
            return;
        }
 
        // Show loader
        loaderDiv.style.display = "block";
 
        try {
            const response = await axios.get(`/recommend?input=${inputText}`);
            const recommendedBook = marked.parse(response.data);
 
            if (recommendedBook) {
                recommendationDiv.innerHTML = `
                      <h3>Recommended Book:</h3>
                      <p>${recommendedBook}</p>
                  `;
            } else {
                recommendationDiv.innerHTML = `
                      <p>No book recommendation available.</p>
                  `;
            }
        } catch (error) {
            console.error(error);
            recommendationDiv.innerHTML = `
                  <p>An error occurred while fetching book recommendation.</p>
              `;
        } finally {
            // Hide loader
            loaderDiv.style.display = "none";
        }
    });
});


Javascript




// server.js
const express = require("express");
const axios = require("axios");
const dotenv = require("dotenv");
const { OpenAI } = require("openai");
 
dotenv.config();
 
const app = express();
const PORT = process.env.PORT || 3000;
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
 
const openai = new OpenAI({ apiKey: OPENAI_API_KEY });
 
app.use(express.static("public"));
 
app.get("/recommend", async (req, res) => {
    try {
        const userInput = req.query.input;
        const completion = await openai.chat.completions.create({
            messages: [
                {
                    role: "system",
                    content: "You are helpful in recommending books."
                },
                {
                    role: "user",
                    content: userInput + "\n list out all books"
                },
            ],
            model: "gpt-3.5-turbo",
        });
        const recommendedBook = completion.choices[0].message.content;
        res.send(recommendedBook);
    } catch (error) {
        console.error(error);
        res.status(500).send(`
    An error occurred while processing your request.`);
    }
});
 
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});


Run the following command to start the server:

node server.js

Output:

1-(online-video-cuttercom)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads