Rayan Slim Rayan Slim - 2 months ago 26
Node.js Question

When to use ../ vs ./ in Node.js require()

var User = require('../models/user');

So In Visual studio, I created a folder called models, and a file inside it called user.js . From what I learned it would make sense to put ./models/user instead of the two dots. Although, that gives me a crash, I was wondering what could be the reason for that. Thank you

rsp rsp

. (one dot) is the current directory

.. (two dots) is the parent directory

Whichever one you use depends on what do you want to load.


Let's say that you have those file structure:

- app
  - dir1
    - file1.js
    - file2.js
  - dir2
    - file3.js

To use file2.js from file1.js you need:


because those files are in the same directory.

But to use file3.js from file1.js you need:


because you need to start from one directory up than the current one.

Of course to use file2.js from file1.js this would also work:


or even this:


or even a crazy path like this:


This is not Node.js specific. It works the same as it would do in the shell or in HTML or anything. One dot is the current dir, two dots is the parent dir.