Search code examples
relative-path

The relative file path suggests a different folder structure?


I have the below folder/file structure:

  1. bmi-calculator > public > styles.css
  2. bmi-calculator > views > index.ejs
  3. bmi-calculator > bmi-calculator.js

In my index.ejs file, I have the following lines to link the css file and the js script:

<link rel="stylesheet" href="../public/styles.css">
<script src="../bmi-calculator.js" async defer></script>

However, the css styles sheet isn't linking correctly (the JS file does), but when it is changed to this it links:

<link rel="stylesheet" href="styles.css">

Futhermore, when I change the script to:

<script src="bmi-calculator.js" async defer></script>

My js file continues to link up correctly. However, the above would suggest the following folder structure:

  1. bmi-calculator > views > index.ejs
  2. bmi-calculator > views > bmi-calculator.js
  3. bmi-calculator > views > styles.css

Also, I'm not sure if this changes anything, but in my bmi-calculator.js file I have app.use(express.static('public')); included in as well and I am running the script by using nodemon bmi-calculator.js.

I've read about relative file paths, but this isn't working as I would expect! Why isn't this working as it should?


Solution

  • The express.static sets your context for static files to the public directory. So in your static files, the path to be defined is relative to that context. So you'll be able to access anything in the public directory without doing:

    ../public/abc.css