Unable to deploy Node.js app on A2Hosting – ENOENT: no such file or directory

Unable to deploy my node app on A2Hosting, getting below error:

Error: ENOENT: no such file or directory, stat ‘/home/eduonli1/portfolio_app/public/index.html’

URL: psrajput.com

domain_details

Node deployment page:

Run NPM Install is successful, but Run JS script keeps loading

node_application_deployment

Anyways, when I go the url, I get:
Error: ENOENT: no such file or directory, stat ‘/home/eduonli1/portfolio_app/public/index.html’

But the file exist in the above path:

CP_File_Manager

My overall folder structure:

portfolio/
│
├── app.js
├── package.json
├── public/
│   ├── css/
│   │   ├── styles.css
│   ├── js/
│   │   ├── script.js
│   ├── images/
│   │   ├── image1.jpg
│   │   └── image2.png
│   ├── fonts/
│   │   ├── font1.woff
│   │   └── font2.ttf
│   └── html/
│       ├── index.html
│       └── mail-success.html
└── .htaccess

app.js:

const express = require("express");
const bodyParser = require("body-parser");
const nodemailer = require("nodemailer");
const dotenv = require("dotenv");
const path = require("path");
const rateLimit = require("express-rate-limit");

dotenv.config();

const app = express();
const port = process.env.PORT || 3131;

// Middleware to parse JSON bodies
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Serve static files
app.use("/assets", express.static(path.join(__dirname, "public", "assets")));
app.use("/css", express.static(path.join(__dirname, "public", "css")));
app.use("/js", express.static(path.join(__dirname, "public", "js")));

// Rate limiting middleware
const limiter = rateLimit({
    windowMs: 60 * 60 * 1000, // 1 hour
    max: 5, // limit each IP to 5 requests per windowMs
    message: "Too many requests from this IP, please try again later",
});

app.use("/send-email", limiter);

// Route to handle form submission
app.post("/send-email", (req, res) => {
    const { name, email, message } = req.body;

    console.log("Form data received:", { name, email, message });

    // Create a Nodemailer transporter
    const transporter = nodemailer.createTransport({
        service: "Gmail",
        auth: {
            user: process.env.GMAIL_USER,
            pass: process.env.GMAIL_PASS,
        },
    });

    // Email message options
    const mailOptions = {
        from: email,
        to: process.env.RECIPIENT_EMAIL,
        subject: "New contact form submission",
        text: `Name: ${name}nEmail: ${email}nMessage: ${message}`,
    };

    console.log("Attempting to send email with options:", mailOptions);

    // Send email
    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            console.error("Error sending email:", error);
            res.status(500).send("Failed to send email");
        } else {
            console.log("Email sent successfully:", info.response);
            // Send mail-success.html
            res.sendFile(path.join(__dirname, "public", "mail-success.html"), () => {
                // Redirect to index.html after 5 seconds
                setTimeout(() => {
                    res.redirect("/");
                }, 5000);
            });
        }
    });
});

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


// Start server
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});

Consistent Data Access Across Nested Routes in Remix”

I recently discovered that you can retain data across nested routes using the <Outlet /> component. Here is an example:

//dash.tsx
import { Outlet, json, useLoaderData } from "@remix-run/react";
import { getSession } from "~/utils/session.server";

export async function loader({ request }) {
  let session = await getSession(request.headers.get("Cookie"));
  return json({ user: session.user });
}

export default function DashRoute() {
  const { user } = useLoaderData();

  return (
    <main className="flex h-screen shadow w-full">
      <Outlet context={user} />
    </main>
  );
}
//childView.tsx
import { useOutletContext } from "@remix-run/react";

function Child() {
  const user = useOutletContext();
  // ...
}

While this method allows the context to be accessible in nested routes, it does not enable data access within the loader of these nested routes. For instance, if you need to fetch posts for a user, you still need to call the getSession() function separately. This approach might lead to inconsistencies if parameters vary across nested routes.

Is there a more consistent way to access data from the root route’s loader in all nested routes? How can we avoid redundant calls to getSession() and ensure consistent parameters across nested routes?

Thank you!

React-Select On change throws ‘ Cannot read properties of undefined (reading ‘value’)’ Error

I am just getting started with React and having difficulty in passing the value of the selected dropdown value to the backend. Sharing the code below for reference, any help would be highly appreciated.

On trying to select a value from dropdown, the following error is being thrown. My end goal is to pass the selected value to the backend on form submit

Error
 Cannot read properties of undefined (reading ‘value’)

import React, { useState, useEffect } from 'react'
import Select from 'react-dropdown-select';
import axios from 'axios';

function App() {

  const [data, setData] = useState([]);
  const [value, setValue] = useState([]);
  const [message, setMessage] = useState("");

   const handleSubmit = (event) => {
    event.preventDefault();
    alert(value)
    console.log("Selected value:", value);
    axios.post("./getEmployeeData", {
      value,
    }).then((response) => {
      console.log(response);
    }).catch((error) => {
      console.log(error);
    });
  };

  useEffect(() => {
    fetch("/listEmployees")
      .then((response) => response.json())
      .then((employee) => {
        const parsed = JSON.parse(employee.employeeData);
        const employees = Object.entries(parsed).map(([key, value]) => ({
          label: value,
          value: value
        }));

        setData(employees);
        console.log(parsed, employees);
      });
  }, []);

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <Select
          name="select"
          options={data}
          multi
          onChange={(option) => setValue(option.target.value)
        }
        />;

        <button type="submit"></button>
        <div className="message">{message ? <p>{message}</p> : null}</div>
      </form>
    </div>
  )
}

export default App;

JavaScript Filter Issue with Collapsible Rows in Laravel Blade Template

im relatively new to web development and im encountering an issue with my js code. ive implemented a filter functionality using js in my website but it seems to have interfered with the collapse feature to and made it stop working properly. but the collapse functionality works again when clearing the filters ive looked into the site who could have the same problem as me but i cant seem to make them work on my code

heres my setup:

  • i have a table where each row can be collapsed to view additional information
  • ive added js filtering to filter the rows based on certain colums
  • the filter works fine but when a filter is active i cant open the collapsed rows to view the details
  • i have my app.blade.php in layouts directory and i store the scripts and styles there that i generally use

Heres my code:

@extends('layouts.app')

@section('content')
    <div class="container">

        <button class="btn btn-success mb-3" id="toggleFilterForm">
            <i class="fas fa-filter"></i> Hide Filter
        </button> 

        <div id="filterForm">
            <div class="row mb-3">
                <div class="col">
                    <input type="text" id="col1" class="form-control" placeholder="Engineer Code">
                </div>
                <div class="col">
                    <input type="text" id="col2" class="form-control" placeholder="Live">
                </div>
                <div class="col">
                    <input type="text" id="col3" class="form-control" placeholder="Status">
                </div>
                <div class="col">
                    <input type="date" id="col4" class="form-control">
                </div>
                <div class="col">
                    <button id="applyFilters" class="btn btn-primary">
                        <i class="fas fa-search"></i> Filter
                    </button>
                </div>
                <div class="col">
                    <button id="clearFilters" class="btn btn-secondary">
                        <i class="fas fa-times-circle"></i> Clear Filters
                    </button>
                </div>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-striped" id="dataTable">
                <thead>
                    <tr>
                        <th>Col 1</th>
                        <th>Col 2</th>
                        <th>Col 3</th>
                        <th>Col 4</th>
                        <th>Date Time</th>
                    </tr>
                </thead>
                <tbody id="tableBody">
                @foreach($fileData as $fileIndex => $file)
                    <tr data-bs-toggle="collapse" data-bs-target="#collapse{{ $fileIndex }}" aria-expanded="false" aria-controls="collapse{{ $fileIndex }}">
                        <td>{{ $file['content']['col1'] }}</td>
                        <td>{{ $file['content']['col2'] }}</td>
                        <td>{{ $file['content']['col3'] }}</td>
                        <td>{{ $file['content']['col4']) }}</td>
                        <td>{{ date('Y-m-d H:i:s', $file['content']['col5']) }}</td>
                    </tr>
                    @if (!empty($file['content']['data']))
                    <tr>
                        <td colspan="5" class="p-0">
                            <div class="collapse" id="collapse{{ $fileIndex }}">
                                <div class="card card-body">
                                    <table class="table table-bordered">
                                        <thead>
                                            <tr>
                                                <th>
                                                    <button class="btn btn-danger" onclick="toggleCollapse('collapse{{ $fileIndex }}')"><i class="fas fa-times"></i> Close</button>
                                                </th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                                <tr>
                                                    <td data-bs-toggle="collapse" data-bs-target="#collapse{{ $fileIndex }}-{{ $subKeyIndex }}" aria-expanded="false" aria-controls="collapse{{ $fileIndex }}-{{ $subKeyIndex }}">{{ $subKeyIndex }}</td>
                                                    <td colspan="5">{{ count($subKey) }} Record(s)</td>
                                                </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </td>
                    </tr>
                    @endif
                @endforeach
                </tbody>
            </table>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {

            document.getElementById('applyFilters').addEventListener('click', function() {
                const engineerCode = document.getElementById('engineerCode').value.toLowerCase();
                const live = document.getElementById('live').value.toLowerCase();
                const status = document.getElementById('status').value.toLowerCase();
                const date = document.getElementById('date').value;

                const topLevelRows = document.querySelectorAll('#tableBody > tr');

                topLevelRows.forEach(row => {
                    const cols = row.getElementsByTagName('td');

                    const engineerCodeText = cols[0] ? cols[0].innerText.toLowerCase() : '';
                    const liveText = cols[1] ? cols[1].innerText.toLowerCase() : '';
                    const statusText = cols[2] ? cols[2].innerText.toLowerCase() : '';
                    const dateText = cols[4] ? cols[4].innerText.split(' ')[0] : '';

                    let match = true;
                    if (engineerCode && !engineerCodeText.includes(engineerCode)) match = false;
                    if (live && !liveText.includes(live)) match = false;
                    if (status && !statusText.includes(status)) match = false;
                    if (date && dateText !== date) match = false;

                    if (match) {
                        row.style.display = '';
                    } else {
                        row.style.display = 'none';
                    }
                });
            });

            document.getElementById('clearFilters').addEventListener('click', function() {
                document.getElementById('engineerCode').value = '';
                document.getElementById('live').value = '';
                document.getElementById('status').value = '';
                document.getElementById('date').value = '';

                const rows = document.querySelectorAll('#tableBody > tr');
                rows.forEach(row => row.style.display = '');

            });

            document.getElementById('toggleFilterForm').addEventListener('click', function() {
                const filterForm = document.getElementById('filterForm');
                if (filterForm.style.display === 'none') {
                    filterForm.style.display = 'block';
                    this.innerHTML = '<i class="fas fa-filter"></i> Hide Filter';
                } else {
                    filterForm.style.display = 'none';
                    this.innerHTML = '<i class="fas fa-filter"></i> Show Filter';
                }
            });
    </script>

@endsection

I expect to be able to open rows to view their info while a filter is active but it doesnt work

Angular Material – Display different text in dropdown view instead of options selected

I have a multi-select dropdown where there’s a option as “ALL” which selects all the options in the list. My requirement is when “ALL” is selected or user manually selects all the option, then in the view “ALL” should show instead of the options selected and the value in the FormControl will also get set as ALL else whatever the user had selected.

This is the Stackblitz project I created for trying the solution.

What approach should I take for this? I know the general rule of dropdown is to show the option label in the view.

How to get translations to build on each other

I am creating a sorting algorithm visualizer that swaps div elements using translate inside keyframe animations. However, if an animation acts on the same element twice, its position resets to the beginning and the animation gets messed up. How can I make it so its position saves and the new animation begins sliding from where the previous animation left off?

const elements = [];
function runSort(){
    for(var i = 1; i <= 5; i++){
        elements.push(document.getElementById(i));
    }
    bubbleSort();
}

async function bubbleSort(){
    for(var i = elements.length -1; i > 0; i--){
        for(var j = 0; j < i; j++){
            if(parseInt(elements[j].innerHTML) > parseInt(elements[j+1].innerHTML)){
                elements[j].style.animationName = "slideRight";
                elements[j+1].style.animationName = "slideLeft";
                await sleep("1000"); //let animation finish running 

                temp = elements[j];
                elements[j] = elements[j+1];
                elements[j+1] = temp
            }
        }
    }
    elements.forEach((element) => console.log(element.innerHTML));  //prints sorted array
}

//to let animation finish running
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

Here is my HTML:

    <div id = container>
        <div id = "1" class = element >1</div>
        <div id = "2" class = element >12</div>
        <div id = "3" class = element >4</div>
        <div id = "4" class = element >3</div>
        <div id = "5" class = element >19</div>
    </div>

Cannot Register Slash Commands while Building my Discord Bot

I have trying my hands out in building my own Discord Bot. I have tuned it to reply on any message from the user. I have built it entirely by reading the documentation on discord.js. The reply thing is working perfectly. However, as per the code in the documentation to register a slash command it’s not working with me:-(

*I have refreshed and pasted the TOKEN in my code and the CLIENT_ID too.

edit:- It’s not showing any error on the console as well.

//Here is my Code

import { REST, Routes } from 'discord.js';
const TOKEN = '**********************************';
const CLIENT_ID = '************';

const commands = [
  {
    name: 'ping',
    description: 'Replies with Pong!',
  },
];

const rest = new REST({ version: '10' }).setToken(TOKEN);

try {
  console.log('Started refreshing application (/) commands.');

  await rest.put(Routes.applicationCommands(CLIENT_ID), { body: commands });

  console.log('Successfully reloaded application (/) commands.');
} catch (error) {
  console.error(error);
}

Extending jQuery with toggleRow – Uncaught ReferenceError: isHiddenWithinTree is not defined?

Trying to duplicate the jQuery toggle() function but to use table-row instead of block as the display value.

I took the existing functions and added a jQuery.fn.extend() as defined below Note: I left showHideRow unmodified from the showHide for the test to ensure it would work as toggle() works now

<script src="/includes/js/jquery.min.js"></script>
<script type="text/javascript">

jQuery.fn.extend( {
    showHideRow: function( elements, show ) {
        var display, elem,
            values = [],
            index = 0,
            length = elements.length;

        // Determine new display value for elements that need to change
        for ( ; index < length; index++ ) {
            elem = elements[ index ];
            if ( !elem.style ) {
                continue;
            }

            display = elem.style.display;
            if ( show ) {

                // Since we force visibility upon cascade-hidden elements, an immediate (and slow)
                // check is required in this first loop unless we have a nonempty display value (either
                // inline or about-to-be-restored)
                if ( display === "none" ) {
                    values[ index ] = dataPriv.get( elem, "display" ) || null;
                    if ( !values[ index ] ) {
                        elem.style.display = "";
                    }
                }
                if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) {
                    values[ index ] = getDefaultDisplay( elem );
                }
            } else {
                if ( display !== "none" ) {
                    values[ index ] = "none";

                    // Remember what we're overwriting
                    dataPriv.set( elem, "display", display );
                }
            }
        }

        // Set the display of the elements in a second loop to avoid constant reflow
        for ( index = 0; index < length; index++ ) {
            if ( values[ index ] != null ) {
                elements[ index ].style.display = values[ index ];
            }
        }

        return elements;
    },
    showRow: function() {
        return showHideRow( this, true );
    },
    hideRow: function() {
        return showHideRow( this );
    },
    toggleRow: function( state ) {
        if ( typeof state === "boolean" ) {
            return state ? this.showRow() : this.hideRow();
        }

        return this.each( function() {
            if ( isHiddenWithinTree( this ) ) {
                jQuery( this ).showRow();
            } else {
                jQuery( this ).hideRow();
            }
        } );
    }
} );

jQuery(function($) {
    $('.expandChildTable').on('click', function() {
        $(this).toggleClass('selected').closest('tr').next().toggleRow();
    })
});
</script>

The error received was: Uncaught ReferenceError: isHiddenWithinTree is not defined?

I noticed I was using the .min version and though that must be it, so I redid things using the .min version as below (*Note: On this one I setup the correct display value to be table-row:

<script src="/includes/js/jquery.min.js"></script>
<script type="text/javascript">

jQuery.fn.extend( {
    showHideRow: function( e, t ) {
        for(var n,r,i,o,a,s,u,l=[],c=0,f=e.length;c<f;c++)(r=e[c]).style&&(n=r.style.display,t?("none"===n&&(l[c]=_.get(r,"display")||null,l[c]||(r.style.display="")),""===r.style.display&&ee(r)&&(l[c]=(u=a=o=void 0,a=(i=r).ownerDocument,s=i.nodeName,(u=ne[s])||(o=a.body.appendChild(a.createElement(s)),u=ce.css(o,"display"),o.parentNode.removeChild(o),"none"===u&&(u="table-row"),ne[s]=u)))):"none"!==n&&(l[c]="none",_.set(r,"display",n)));for(c=0;c<f;c++)null!=l[c]&&(e[c].style.display=l[c]);return e
    },
    showRow: function() {
        return showHideRow( this, true );
    },
    hideRow: function() {
        return showHideRow( this );
    },
    toggleRow:function(e){
        return"boolean"==typeof e?e?this.showRow():this.hideRow():this.each(function(){ee(this)?ce(this).showRow():ce(this).hideRow()})
    }
}); 

jQuery(function($) {
    $('.expandChildTable').on('click', function() {
        $(this).toggleClass('selected').closest('tr').next().toggleRow();
    })
});
</script>

However I still get: Uncaught ReferenceError: ee is not defined

Help!! Why can’t it call those functions since jQuery is already loaded and my new functions are in the jQuery extension?

TIA!!

I’m using React-Router-Dom for page routes. I need to separate admin routes from public ones. Can you suggest a Solution?

I am using React-Router-Dom for page routes. I need to separate admin routes from public ones.Can anyone tell me how do i do it.

App.js

import { createBrowserRouter,RouterProvider } from "react-router-dom";
import HomePage from "./Pages/home";
import Contact from './Pages/contact';
import AboutPage from "./Pages/About";
import RootLayout from "./Pages/Root";
import ErrorPage from "./Pages/error";
import ProductPage from "./Pages/Product";
import ProductDetails from "./Pages/ProductDetails";

const router = createBrowserRouter([
  {
      path: '/',
      elements: <RootLayout />,
      errorElement: <ErrorPage />,
      children: [
        {path:'/', element:<HomePage />},
          { path: 'contact', element: <Contact /> },
          { path: 'about', element: <AboutPage /> },
          { path: 'product', element: <ProductPage /> },
          { path: 'product/:productId', element: <ProductDetails /> },
      ],
  },
]);

function App() {
  return (
  <RouterProvider router={router} />
  );
}

export default App;

I want admin Routes that are only accessible to admins only.

Error: Cannot read properties of undefined (reading ‘name’)

Error: Cannot read properties of undefined (reading ‘name’)
at renderWithHooks (/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_client_ReactRefreshEntry_js-node_mod-b8ae68.iframe.bundle.js:42707:18))
at mountIndeterminateComponent (/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_client_ReactRefreshEntry_js-node_mod-b8ae68.iframe.bundle.js:48455:13))
at beginWork$1 (/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_client_ReactRefreshEntry_js-node_mod-b8ae68.iframe.bundle.js:50044:16))
at beginWork (/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_client_ReactRefreshEntry_js-node_mod-b8ae68.iframe.bundle.js:58513:14))
at performUnitOfWork (/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_client_ReactRefreshEntry_js-node_mod-b8ae68.iframe.bundle.js:57334:12))
at workLoopSync (/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_client_ReactRefreshEntry_js-node_mod-b8ae68.iframe.bundle.js:57050:5))
at renderRootSync (/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_client_ReactRefreshEntry_js-node_mod-b8ae68.iframe.bundle.js:57005:7))
at recoverFromConcurrentError (/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_client_ReactRefreshEntry_js-node_mod-b8ae68.iframe.bundle.js:56183:20))
at performConcurrentWorkOnRoot (/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_client_ReactRefreshEntry_js-node_mod-b8ae68.iframe.bundle.js:56128:26))

tried to handle validation in the register components via props from the RegisterForm

Why it’s not true that every function object has a `prototype` property? [duplicate]

I’m trying to understand some details of the following statement:

constructor is a pre-defined [[DontEnum]] property of the object pointed to by the prototype property of a function object and will initially point to the function object itself.

Intuitively, I was trying to rephrase it like this:

Every function object has a prototype property that points to a special object by default. The object has a constructor property (a pre-defined [[DontEnum]] property), which points back to the function object.

But I was told this was wrong. Why? Is it only because we can directly set it to null after creation?

Why does this js import fail in a nix build but succeed in a nix devshell?

I have a flake.nix with this derivation in the outputs:

packages.svg = pkgs.stdenv.mkDerivation rec {
  name = "generate-svg";
  src = self;
  buildInputs = [ pkgs.nodePackages.nodejs ];
  buildPhase = ''
    export NODE_PATH=${src}/node_modules:${src}
    node ${src}/generate.js
  '';

  installPhase = ''
    mkdir -p $out
    cp output.svg $out/
  '';
};

You can see the whole file (and others) here: https://github.com/MatrixManAtYrService/buildsvg

My goal is that the following command should run generate.js which will use d3.js to build a svg file defined by the contents of generate.js.

$ nix build 'github:MatrixManAtYrService/buildsvg#svg'
$ ls result
    output.svg

Instead, the nix build command fails with this error:

Error: Cannot find package '/nix/store/a76p6qgrxlx0safvxrqx5aknhszvg703-source/node_modules/opentype.js/package.json' imported from /nix/store/a76p6qgrxlx0safvxrqx5aknhszvg703-source/generate.js
    at legacyMainResolve (node:internal/modules/esm/resolve:215:26)
    at packageResolve (node:internal/modules/esm/resolve:841:14)
    at moduleResolve (node:internal/modules/esm/resolve:927:18)
    at defaultResolve (node:internal/modules/esm/resolve:1157:11)
    at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:390:12)
    at ModuleLoader.resolve (node:internal/modules/esm/loader:359:25)
    at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:234:38)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:87:39)
    at link (node:internal/modules/esm/module_job:86:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}
Node.js v20.12.2

The top of generate.js looks like this:

import fs from 'fs';
import * as d3 from 'd3';
import opentype from 'opentype.js';  // <--- failure is here
import D3Node from 'd3-node';

So I know that some of my modules are being imported correctly.
Also, If I use a nix devshell, it works fine:

devShells.default = pkgs.mkShell {
  buildInputs = [
    pkgs.nodePackages.nodejs
  ];
  shellHook = ''
    export NODE_PATH=$PWD/node_modules
  '';
};

$ nix develop
$ node generate.js
SVG generated successfully.

My package.json indicates these dependencies, and I’ve run npm install which caused them to be downloaded into node_modules (pardon if this is obvious, I’m a nodejs newbie).

I have sprinkled ls statements into the buildPhase and verified that /nix/store/a76p6qgrxlx0safvxrqx5aknhszvg703-source/node_modules/opentype.js/package.json does indeed exist, despite what the error says.

Why is my nix build failing, while the same build works in a devshell?