Rayan Slim Rayan Slim - 1 month ago 15
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
Answer

. (one dot) is the current directory

.. (two dots) is the parent directory

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

Example:

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:

require('./file2.js');

because those files are in the same directory.

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

require('../dir2/file3.js');

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:

require('../dir1/file2.js');

or even this:

require('../../app/dir1/file2.js');

or even a crazy path like this:

require('./././../../app/../app/../app/dir1/file2.js');

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.