0 votes
in Programming by (580 points)

I recently deployed my first Node JS app on shared hosting with Namecheap. The app is essentially just a static website with an integrated contact form so nothing out of this world.

Unfortunately, the website keeps crashing every few days because it hits the maximum number of background processes set by the webhost. According to hosting support, the problem is related to the Node JS processes running non-stop and thus accumulating until they reach the limit. Would anyone know how to fix this issue?

Thanks a lot in advance, attaching my code for reference.

const express = require("express");
const app = express();

const path = require("path");

const nodemailer = require("nodemailer");

const Joi = require("joi");

app.use(express.static("public"));

app.use(express.json());

app.get("/", (req, res) => {
    res.sendFile(path.join(__dirname, "public", "index.html"));
});

app.get("/about", (req, res) => {
    res.sendFile(path.join(__dirname, "public", "about.html"));
});

app.get("/projects", (req, res) => {
    res.sendFile(path.join(__dirname, "public", "projects.html"));
});

app.get("/contact", (req, res) => {
    res.sendFile(path.join(__dirname, "public", "contact.html"));
});

app.post("/", (req, res) => {
    const transporter = nodemailer.createTransport({
        service: "gmail",
        auth: {
            user: "example.abc@gmail.com",
            pass: "example.xyz"
        }
    });
    const data = req.body;
    console.log(data);
    const schema = Joi.object({
        name: Joi.string().required(),
        email: Joi.string().email().required(),
        subject: Joi.string().required(),
        message: Joi.string().required()
    });
    const validatedData = schema.validate(data);
    console.log(validatedData);
    if (validatedData.error) {
        return res.json({ status: "error" });
    } else {
        const mailOptions = {
            from: data.email,
            to: "example.abc@gmail.com",
            subject: `${data.name}: ${data.subject}`,
            text: data.message + `\n\nEmail Address: ${data.email}`
        };
        transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                return res.json({ status: "error" });
            } else {
                return res.json({ status: "success" });
            }
        })
    }
});

app.use((req, res) => {
    res.redirect("/");
});

app.listen(() => console.log("Connection open"));

Please log in or register to answer this question.

...