Search code examples
javascriptnode.jsexpresspathrequire

How to locate the right path for a .js file when using require


I have an ExpressJS project where I want to use .js module inside another. I use require to get the .js module but it can't find the module because the path is not correct. How can I see or find what is the correct path for a local module.

Here is my project hierarchy/structure enter image description here

This is what I have tried inside programController.js - another thing is I don't quite understand using "." in path string.

var Program = require('.././program.js');
var FinishProgram = require('.././finishProgram');

Solution

  • The . and .. notation in paths represent a path relative to the file they're being required from.

    Meaning of . and .. Wildcards

    . - inside the same directory this file is in (also referred to as the current working directory)

    .. - inside the parent directory of the current directory

    When you use multiples of these together it creates a relative path pattern. So for programController.js to access program.js your path should be

    var Program = require('../../models/program');

    This path means, go up 2 folders to the App directory and locate the models folder, then load the file program.js.

    Following the same rules, you can also access finishProgram.js

    var FinishProgram = require('../../models/finishProgram');