Issue: ENOENT encountered with __dirname usage

When building my website using Express, I encountered an issue with my code in server.js:

app.use(express.static('public'));
app.get('/add', function (req, res) {
res.sendFile(__dirname + "/" + "add.htm");})

The structure of my project is as follows:

core
    server.js
public
    add.html

However, when attempting to access http://localhost:9000/add, I received the following error message:

Error: ENOENT, stat '...\Project\REST\core\add.html' at Error (native)

I am confused as to why it is looking for add.html in the core folder instead of the public folder. Any insights on this issue would be greatly appreciated.

Answer №1

Why is it searching for add.html in the core folder?

The reason behind this is because when using the code `__dirname`, it points to the directory of the JavaScript file where it's being used (not the current working directory).

In your specific scenario, the file using this code is `core/server.js`, therefore __dirname refers to `FULL-PATH-TO/core/`.

To find the path to add.html, relative to server.js, you can use the following:

__dirname + "/../public/add.html"

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

Is there a radio button that can dynamically update and modify the current view?

Although I don't consider my issue to be overly complex, as a newcomer I am struggling to find a straightforward solution. The form I have collects various items and on the output page generates a table based on this data. For instance, one question ...

using node js to make an angular http get request

When working with MongoDB, I am able to query data and then send it as JSON to a specific URL. In the process of querying data from MongoDB router.get('fillSurvey/:ID', function (req, res) { Survey.findOne({_id:req.params.ID}, function ( ...

Issue with NPM Build

Having trouble executing the following command: npm run build. The package.json file contains the following script definitions: "scripts": { "start": "npm run build", "build": "webpack -d, --devtool && c ...

How come the likes are not being refreshed when the button is clicked in my mongoose schema?

I am currently working on an express app using nodejs and mongoose. My main goal is to implement a JavaScript function that can update the number of likes on a post in a database directly from my ejs file. However, I have encountered troubles with this tas ...

The static side of the class `typeof _Readable` is erroneously extending the static side of the base class `typeof Readable`

I am currently developing a Discord bot using node/typescript. After running the typescript compiler on my code, I encountered this error: node_modules/@types/readable-stream/index.d.ts(13,15): error TS2417: Class static side 'typeof _Readable' ...

encountering difficulties while installing node-sass using npm

As I work on creating a local environment for PrestaShop, I am facing an issue during the npm installation process. There seems to be an error occurring when trying to install node-sass. Can someone provide guidance on resolving this issue? ...

Having trouble with request-promise in node.js? It's not functioning as anticipated

Currently utilizing the request-promise node module. Following the documentation closely to ensure correct setup, however encountering the following error: Unhandled rejection StatusCodeError: 400 - "{\n \"error\" : {\n \"s ...

What is the mechanism behind the operation of asynchronous functions within the bcrypt() method in Node.js?

const bcrypt = require('bcrypt'); const saltRounds = 8; const plainPassword1 = "12345"; const plainPassword2 = "56789"; const func1 = async (password, plainP) => { console.log("hashing password"); const h ...

Although Ionic 2 has been successfully installed, it appears to be missing from the output of the command 'ionic info'

After installing Ionic 2 and Cordova on my Windows system, I encountered an issue where it was not showing up when running 'ionic info'. This prevented me from being able to run my Ionic project. Upon running ionic info, the following output was ...

method in node.js for rendering pages

My question is pretty straightforward. I am currently working with node.js, express, and the jade view engine. When I try to render a file and include HTML tags in an object field, the output ends up looking comical. Here's an example: app.js res.ren ...

Utilize the npm command following the execution of any other command

Currently, I'm utilizing cmder in Windows 8.1. After installing node.js with npm, I set up an alias for npm in cmder. However, when I check if everything is functioning properly using npm --version, the output I receive is: npm config help Usage: np ...

Steps for converting a Calendar into a JSON format

I am working on developing a REST application like the one shown below: @XmlRootElement @Entity @Table(name = "tb_verarq") public class Verificacao implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue ...

express-validator: bypass additional validation in a user-defined validator

Utilizing the express-validator package for validating my request data. As per the documentation, we need to declare them in this manner: app.use(expressValidator({ customValidators: { isArray: function(value) { return Array.isArray(value); ...

Eliminate redundant items from the array

"name": [ { "name": "test1" }, { "name": "test2" }, { "name": "test3" }, { "name": "test1" }, ] Generated by a Node.js script, the structure ab ...

Having trouble fetching an image file in Node.js after submitting it from React

Trying to send an image file from react to nodejs has been a challenge. I have implemented the SetImage function to set the selected image file to the 'myimage' state variable, and then used Axios to post the images to the '/blog/posts' ...

Troubleshooting issue with multer code failing to save files in designated directory within nodejs server when using reactjs frontend

I'm facing an issue while trying to upload a photo into my server folder. Even though the submission process adds the picture to my database, it does not display the image in my server folder. The frontend of my application is built using React JS, an ...

The script from '*' is being denied execution because its MIME type ('application/json') is not executable, and a strict MIME type check is in place

Here is the code I used to retrieve data from the confluence rest api: <script type="text/javascript" src="Scripts/jquery.min.js"></script> <script> $.ajax({ type: "GET", url: "https://blog.xxxxx.com/rest/api/content? ...

What is the process for incorporating Express.js variables into SQL queries?

Recently delving into the world of node.js, I've embarked on a journey to create a login and registration system using express.js, vanilla JS, CSS, HTML, and MySql. Within the following code lies the logic for routing and handling HTTP Post requests ...

Controlling the document object model of a third-party website within the Electron framework

I am completely new to electron. My main goal is to load a URL and then execute some Javascript that will make changes to the DOM. Currently, my approach involves creating a BrowserWindow that loads the URL, and I understand that I can utilize webContents ...

Utilizing Sequelize - Establishing relationships and querying data from related tables

I have successfully implemented 3 SQL tables with Sequalize, and here are the schemas: Loans id: DataTypes.INTEGER, book_id: DataTypes.INTEGER, patron_id: DataTypes.INTEGER, loaned_on: DataTypes.DATE, return_by: DataTypes.DATE, returned_on: DataTypes.DA ...