Newbie seeking assistance: Troubleshooting Nodejs error - ENOENT: no file or directory found. Can someone please help?

I attempted to follow an online course on YouTube, mirroring the steps of the instructor. When I encountered an error, I diligently re-watched the video segment multiple times, searched for solutions on Google, and read through numerous similar problems on StackOverflow and other websites with no success. As a beginner in programming, I am currently learning and would greatly appreciate any assistance. The files potentially related to this issue are: server.js, script.js, style.css

server.js

const http = require('http')
const fs = require('fs')
const path = require('path')

http.createServer((req, res) => {

    const file = req.url === '' ? 'index.html' : req.url
    const filePath = path.join(__dirname, 'public', file)
    const extname = path.extname(filePath)

    const allowedFileTypes = ['.html', '.css', '.js']
    const allowed = allowedFileTypes.find(item => item == extname)

    if(!allowed) return

    fs.readFile(
        filePath,
        (err, content) => {
            if(err) throw err

            res.end(content)
        }
    )

}).listen(5000, () => console.log('Server is running'))

script.js

const ul = document.querySelector("ul")
const input = document.querySelector("input")
const form = document.querySelector('form')


function addElement({ name, url }) {
    const li = document.createElement('li')
    const a = document.createElement("a")
    const trash = document.createElement("span")

    a.href = url
    a.innerHTML = name
    a.target = "_blank"

    trash.innerHTML = "x"
    trash.onclick = () => removeElement(trash)

    li.append(a)
    li.append(trash)
    ul.append(li)
}

function removeElement(el) {
    if (confirm('Are you sure you want to delete?'))
        el.parentNode.remove()
}

form.addEventListener("submit", (event) => {
    event.preventDefault();

    let { value } = input

    if (!value) 
        return alert('Please fill out the field')

    const [name, url] = value.split(",")

    if (!url) 
        return alert('Format the text correctly')

    if (!/^http/.test(url)) 
        return alert("Enter the URL correctly")

    addElement({ name, url })

    input.value = ""
})

style.css

@import url('https://fonts.googleapis.com/css2?family=Quicksand:wght@300;600&display=swap');

* {
  box-sizing: border-box;
}

html {
  font-size: 62.5%;
}

body {
  font-family: 'Quicksand', sans-serif;
  
  background: #7159c1;
}

.container {
  width: 80%;
  max-width: 400px;
  
  margin: auto;
}

h1 {
  text-align:center;
  color: white;
  
  font-size: 3.4rem;
}

input {
  width: 100%;
  
  padding: 8px 16px;
  margin-bottom: 32px;
  
  border-radius: 16px;
  border: 1px solid #ccc;
  
  outline: none;
  
  font-size: 1.6rem;
  font-weight:300;
}

ul {
  background: white;
  
  box-shadow: 0px 4px 8px -2px #00000033;
  border-radius: 6px;
  border: 1px solid #ddd;
  
  padding: 16px;
  
  font-size: 1.4rem;
  
}

li {
  list-style: none;
  
  display:flex;
  align-items: center;
  justify-content: space-between;
  
  border-bottom: 1px solid #ddd;
}


a {
  display: block;
  
  color: #333;
  text-decoration: none;  
  
  padding: 16px 0;
  font-size: 1.8rem;
  
}

a:hover {
  font-weight: bold;
}

li:first-child,
li:last-child {
  border: none;
}

li span {
  cursor:pointer;
}

Answer №1

You could simply use return res.end() under two circumstances. The first being when !allowed is true and the second being if the FILE does not exist (this error occurs when fs attempts to access a nonexistent file). The only modification required is in your server.js file.

const http = require('http')
const fs = require('fs')
const path = require('path')
const isFile=(path)=>fs.lstatSync(path).isFile() //checks if something is a file or not

http.createServer((req, res) => {

    const file = req.url === '' ? 'index.html' : req.url
    const filePath = path.join(__dirname, 'public', file)
    const extname = path.extname(filePath)

    const allowedFileTypes = ['.html', '.css', '.js']
    const allowed = allowedFileTypes.find(item => item == extname)

    if(!allowed){return res.end()} //res.end to END the request
    let existingFiles=fs.readdirSync().filter(isFile)
    if(!existingFiles.includes(path)){
        console.log("faulty path requested",path)
        //I'm guessing that your index.html is causing this issue, hence I'm displaying the attempted path
        return res.end() //res.end to END the request
    }

    fs.readFile(
        filePath,
        (err, content) => {
            if(err) throw err

            res.end(content)
        }
    )

}).listen(5000, () => console.log('Server is running'))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The jQuery ajax request will only display the data in the HTML once

Hey there! I am facing an issue where, when I click on my button to make an ajax request, it works perfectly and displays the data on my select item. However, on clicking the button again, the data is fetched correctly but the select item shows the data t ...

The module for the class could not be identified during the ng build process when using the --

Encountering an error when running: ng build --prod However, ng build works without any issues. Despite searching for solutions on Stack Overflow, none of them resolved the problem. Error: ng build --prod Cannot determine the module for class X! ...

Which HTML Editing Software is Best for Me?

As a college student, I have completed multiple web development and design courses. Throughout the past few years, I have utilized various tools such as PHPStorm, Visual Studio Code, Notepad++, SublimeText3, and Atom. Although I don't necessarily hav ...

What is the best way to stop webpack from generating typescript errors for modules that are not being used?

The directory structure is set up as follows: └── src ├── tsconfig.json ├── core │ ├── [...].ts └── ui ├── [...].tsx └── tsconfig.json Within the frontend, I am importing a limi ...

Error encountered during webpack development build due to syntax issues

Having trouble building a project with webpack due to persistent syntax errors? It seems like when your friend runs the same code on Linux (while you're working on Windows 10), everything works fine without any errors. Here is the configuration for m ...

Strategies for adjusting text size to fit within a resizable div container

I'm facing an issue with a resizable div that has text inside. When I resize the div, the last line of the text goes beyond the boundaries of the div. How can I ensure that all the text fits within the resizable div while maintaining the appropriate f ...

Make the Height of the Parent Div Based on the Position of its Children

If you're looking to design a card with three child divs, where only one is visible at a time and transitions smoothly as the user progresses through steps 1, 2, and 3, then you've come to the right place. In the code snippet provided below, the ...

Angular JS allows for the creation of a multiple select feature with an additional value linked to each selection

Looking for advice on how to add an additional integer value along with selected values in a multiple select field for my project. Can anyone recommend the best approach for achieving this? Here is a snippet of what my multiple select dropdown currently ...

Customize the serialization of a single object in Newtonsoft.Json

When comparing hashes of serialized objects on the server and client, it is important for the JSON rendering to be identical on both sides. Currently, there is an issue with a number field being serialized differently in JavaScript and .NET - causing the h ...

Trigger a jQuery click event to open a new tab

On a public view of my site, there is a specific link that can only be accessed by authenticated users. When an anonymous user clicks on this link, they are prompted to log in through a popup modal. To keep track of the clicked link, I store its ID and inc ...

Unable to find a hidden JavaScript function

I'm facing an unusual challenge with my project. I'm currently developing a system using JSF2 (Java) and the Primefaces component library. I have multiple buttons triggering a JavaScript function called checkParams() on a onclick event. Now, I ne ...

Click on the checkbox to activate it using JavaScript

I'm trying to use JavaScript to toggle the checkbox status when clicking a button. The first button is supposed to uncheck the box and it's working correctly: function clear() { document.getElementById("check").checked = ""; } However, I al ...

What is the best way to automatically scroll to the chosen option when a button is clicked?

Is there a way to make the select box automatically scroll and show the selected option when the focus button is clicked? The current method I am using with focus does not achieve this. Are there any JavaScript or jQuery methods that can help me solve th ...

Using $resource in AngularJS to remove published content

Recently, I started experimenting with AngularJS and testing out functionalities like posting and deleting content using $resource. Posting works perfectly fine for me, but I encountered a 404 error when trying to delete something that was posted. DELETE ...

I am struggling to grasp the concept of utilizing ui-route

I'm struggling with the correct usage of ui-route. The examples on the angular-ui website aren't providing much help. My goal is to create a basic navigation menu. If the route matches that of the item, I want to display a <span>, otherwis ...

Utilize esbuild to monitor for any modifications, recompile the code, and automatically restart the express server

In my endeavor to develop a basic SSR-powered project using express + react, I find the need to monitor frontend and backend scripts concurrently in the development process. The primary objective is to utilize express routes in directing to react page com ...

Converting a VueJS application with node/express into a single container using Docker

I may be treading on familiar ground here, but I haven't come across a solution that addresses my specific issue. I have a VueJS application running with Express/NodeJS as the server, and while I know the recommended approach is to separate them into ...

Toggle between displaying and concealing content by clicking or hovering the mouse

I have a button that is positioned at the top of the browser. I want to show a dropdown list when the user clicks or hovers over this button. HTML <div class="translator"> <div class="translate-btn">Translator</div> <div class="t ...

What is the best way to configure my card components for a flex display?

Currently, I am in the process of learning React. I have a file named new_card_component.js that is responsible for displaying data fetched from the data.js file. The issue arises in my AirBnB.js file, where I'm passing the AirbnbApp module to a secti ...

When combining CSS grids, nesting them can sometimes cause issues with the height layout

Check out the code on jsFiddle .component-container { width: 800px; height: 200px; background-color: lightyellow; border: 1px solid red; padding: 10px; overflow: hidden; } .component-container .grid-container-1 { display: grid; grid-tem ...