ozata
ozata

Reputation: 562

NodeJs require('../file.js') issues

i am trying to build a nodeJs app with express, sequelize and and sqlite. So in my root directory i have a routers directory where i store '.js' files of express's routers. And again in root directory i have a 'db.js' file. The problem is, when i try to require "db.js" file from the routers folder's '.js' files. it says

    Error: Cannot find module 'db.js'

I'm using require as in the example below

    db = require('../db.js');

Can someone help me find my mistake? Thanks alot

Upvotes: 0

Views: 95

Answers (2)

Bamieh
Bamieh

Reputation: 10906

the root directory is where you start the app by calling node on that js file.

if the file is on the root of that file, you need to write

var db = require('./db'); // same file as yours.

using '../' will go to the parent folder and look there.

using 'db' directly will look in the node_modules for the db module.

Upvotes: 1

leetibbett
leetibbett

Reputation: 843

Your current directory isn't what you think it is, so "../" is failing to go where you think it should. Try something like this:

db = require('path').join(__dirname,'../db.js')

Here is the info on __dirname and path.

Upvotes: 1

Related Questions