1

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

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:

  1. Attempt 1 - Error: Cannot find module './exercises/ex1/FileOne.js'
  2. Attempt 2 - Error: Cannot find module 'FileOne.js'
  3. Attempt 3 - Error: Cannot find module '/exercises/ex1/FileOne.js'
  4. 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

Jordan Papaleo
  • 1,463
  • 11
  • 24

2 Answers2

2

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");
Salem
  • 12,808
  • 4
  • 34
  • 54
1

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.

Community
  • 1
  • 1
ma08
  • 3,654
  • 3
  • 23
  • 36