Reputation: 27
I have a simple node application where i want to include a module named dishRouter.
The directory structure is like this :-
Structure
Dishes/index.js exports the dishRouter that i use in my app.js by
var dishRouter = require('/dishRouter')
When i run app.js using node app, it says : The Error
i tried to print __dirname and it gives
"C:\Users\Kush\Desktop\NodeExamples\Express-example\Assignmnet1"
I do not understand why node cannot find the module 'dishRouter' while it is in the same directory.
Any help is appreciated, and sorry for the messed up structure of questions.
Code in Dishes/index.js :
var DishRouter = require('express').Router();
var fs = require('fs');
var bodyparser= require('body-parser');
DishRouter.use(bodyparser.json());
DishRouter.all('/', function(req,res,next){
res.writeHead(200,{'Content-Type': 'text/plain'});
next();
});
DishRouter.get('/',function(req,res,next){
res.end('Will send the dish list to you!');
});
DishRouter.post('/',function(req,res,next){
res.end('will add the Dish named : '+req.body.name+' and the Description : '+req.body.description);
});
DishRouter.delete('/',function(req,res,next){
res.end('will DELETE all dishes');
});
DishRouter.get('/:dishId',function(req,res,next){
res.end('Will send the dish with name : '+req.params.dishId+' to you!');
});
DishRouter.put('/:dishId',function(req,res,next){
res.end('Update the dish named : '+req.params.dishId+', Details to : '+req.body.description);
});
DishRouter.delete('/:dishId',function(req,res,next){
res.end('will DELETE dish : '+req.params.dishId);
});
module.exports = dishRouter;
var express = require('express');
var fs = require('fs');
var DishRouter = require('./dishRouter');
var routes= express.Router();
var util = require('util');
routes.get('/', (req, res, next) => {
console.log(util.inspect(req));
res.writeHead(200,{'Content-Type': 'text/plain'});
next();
});
routes.delete('/',(req,res)=> {
res.sendStatus(404);
});
routes.use('/dishes', DishRouter);
module.exports = routes;
var express = require('express');
var routes = require('./routes');
var hostname = 'localhost';
var port = 3000;
var app =express();
app.use(express.static(__dirname + '/routes'));
app.use('/', routes);
app.listen(port,hostname,function(){
console.log('Server running on port '+port);
});
Upvotes: 1
Views: 1336
Reputation: 1396
In Dishes/index.js
, the bottom line exports dishRouter
when you want to export DishRouter
(capitalization typo).
In routes/index.js
, you want to use var DishRouter = require('./Dishes/');
since the exported DishRouter
is inside the Dishes
folder.
Upvotes: 1
Reputation: 4035
Instead of var DishRouter = require('./dishRouter');
,
you must use var DishRouter = require('./Dishes');
It doesn't matter what your module exports, what matter is the correct directory path.
Upvotes: 0