I am using node to run some JS tasks. I am using node require to include other needed files that I have written. The files I am trying to include exist in the same directory. There is nothing special about these files; just plain old JavaScript. I am not serving the content to a browser or anything. I am just trying to run JS logic.
My directory structure:
- root
- exercises
- ex1
- FileLoader.js
- FileOne.js
- ex1
- exercises
In my FileLoader.js I ran each one of these file path patterns by itself. They are in the order of my attempts.
require('./exercises/ex1/FileOne.js'); // Attempt 1 path
require('FileOne.js'); // Attempt 2 path
require('/exercises/ex1/FileOne.js'); // Attempt 3 path
require('../../exercises/ex1/FileOne.js'); // Attempt 4 path
Terminal Command:
node ./exercises/ex1/ex1.js
Outcomes:
- Attempt 1 - Error: Cannot find module './exercises/ex1/FileOne.js'
- Attempt 2 - Error: Cannot find module 'FileOne.js'
- Attempt 3 - Error: Cannot find module '/exercises/ex1/FileOne.js'
- Attempt 4 - It worked even though I did not expect to.... FML
So the last one worked but the path needed is pretty silly. It seems like my app does not have a concept of the root. I assumed that node thought my root was ex1. But then I would expect attempt 2 to work. I feel like I am overlooking something stupid.
Question:
- What is the correct way to use file paths with require?
- Is there a way to set a root directory with node?
Thank you,
Jordan