Ryan Tran
Ryan Tran

Reputation: 487

express js - require('config.js')

I confuse about relative url in express js. I have 2 file : app.js and config.js I am in "my_app" folder (application folder) and run app :

In app.js :

var config = require('config.js');
// => throw err : Cannot find module 'config.js'

var config = require('/config.js');
// => throw err : Cannot find module '/config.js'

var config = require('./config.js');
// => throw err : Cannot find module 'http://localhost:3000/config.js'

var config = require(__dirname + '/config.js');
// => throw err : Cannot find module 'http://localhost:3000/config.js'

Where is my_app folder ? It is not in require command though starting inside.

This is my structure :

start
  -- controllers
  -- models
  -- node_modules
  -- public
  -- views
  app.js
  config.js
  package.json
  router.js

Please give me advances! Thanks!

Upvotes: 0

Views: 374

Answers (1)

Aditya K
Aditya K

Reputation: 456

There are 2 types of modules in node, Core modules and user defined modules. Every file that you write is a user defined module. To reference any user defined module, u need to pass the relative path.

"./config.js" - here ./ means that config file is in the current directory (of the file you are working on)
"../config.js" - here ../ means that config file is in the parent directory (of the file you are working on)
__dirname - macro which gives the path of the directory of the file you are working on
__filename - macro which gives the path of the file that you are working on

if you just say "config.js" it means it is a core module and node searches for that module in node_modules folder. If it does not find it there, it searches for the file in the parent directory's node_modules folder and so on. If it still does not find the module, it will throw an error

It is better to use path module to construct paths as it has some easy to use API's and it avoids mistakes. More info here

Upvotes: 2

Related Questions