Bijay Timilsina
Bijay Timilsina

Reputation: 757

Error while importing modules in ExpressJS

I am trying to import some modules in an ExpressJS app but it throws the following error:

Error: Cannot find module './public/js/date.js'
....more error logs...
at Object. (/home/user007/todoApp_SSRendered/routes/route-add.js:2:23)

I have some deeply nested folders with modules all scattered over places. My folder structure is something like this. I think it has something to do with how I am specifying routes for the modules.

enter image description here

My app.js import the module route-main.js located in routes folder

const mainRoute = require('./routes/route-main.js')
app.use('/', mainRoute)

The route-main.js on the other hand imports all the other modules inside the same routes folder

const addTask = require('./routes/route-add.js') + .....other three remaining files...
let taskToUpdate = require('./public/db/tasks.json')

Going a level more deep, all the other 4 files inside routes folder (except route-main.js), require the two files in js folder

const newDateFormat = require('./public/js/date.js')
const writeFile = require('./public/js/writeFile.js')

So overall the module dependency link (require) is something like:

app.js --> main.js --> (route-add, route-delete...) --> (date, writeFile)

Note: In app.js, I only require main.js and so on for the others (there is no double require for the same module). I'm using Express 4.14.1 and have Pug and body-parser as the remaining dependencies.
Also the app is fully server-side rendered if it helps.

THANK YOU :)

Upvotes: 0

Views: 199

Answers (1)

paqash
paqash

Reputation: 2314

This is a relative path issue, since route-main.js and /public are not in the same folder, you need to replace:

let taskToUpdate = require('./public/db/tasks.json')

with

let taskToUpdate = require('../public/db/tasks.json')

And check that when you're requiring files from other folders that the relative path is correct.

Upvotes: 1

Related Questions