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:
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:
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:
Thank you,
Jordan
The right syntax would be require("./FileOne.js"). The second form (require('FileOne.js');) would work if the file was placed in node path.
To set node root you can use NODE_PATH. For example, using
NODE_PATH=/path/to/your/project/root node ex1.js
you could reference FileOne as:
require("exercises/ex1/FileOne.js");
Also consider using __dirname. Check this answer for better insight. Sometimes referencing might depend on where the node command is called from to start the app when dealing with modules like fs. So __dirname would be a safe option to use.
In Node.js, __dirname is always the directory in which the currently executing script resides (see this). In other words, the directory of the script that is using __dirname.
By contrast, . gives you the directory from which you ran the node command in your terminal window (i.e. you working directory). The exception is when you use . with require(), in which case it acts like __dirname.
It's a bit confusing, it is explained clearly in the answer linked.