vendredi 20 février 2015

NodeJs : modules.export : Cannot find one of my own custom module

I am trying to include my own users.js module to my router file. It keeps throwing the error:


Cannot find module './router/users.js'


My directory structure is as follows:


nodejs (Main folder on my drive)


-- expressserver.js (My server file)


-- package.json


-- router (folder containing main.js router and users.js user details file)


----- main.js


----- users.js


----- orders.js


Here my users module is in the same folder as my router (main.js)


My code for router is:



var url = require('url');
var users = require('./router/users.js');

module.exports = function (app) {

app.get('/', function (req, res) {
res.render('index.html');
console.log("Home page displayed");
});
app.get('/login', function (req, res) {
res.render('login.html');
console.log("Log in page displayed");

});

app.post('/login', function (req, res) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;

console.log(query);
console.log("Username: " + query.useremail);
console.log("Password: " + query.password);

validUser = false;

for (var x in USERS.users){
//console.log(USERS.users[x].userid);
if (query.useremail === USERS.users[x].useremail
&& query.password === USERS.users[x].password)
{
validUser = true;
break;
} // end of if

}// end of for

console.log(validUser);

if (validUser === true){
console.log("logged in");
res.render('index.html');
}

});
app.get('/api/orders/:id', function (req, res) {
console.log(req.params.id);
res.json(ORDER.orders[req.params.id]);
});

app.get('/api/orders/', function (req, res) {
console.log(ORDER);
res.json(ORDER);

});
app.get('/api/users/:id', function (req, res) {
console.log(req.params.id);
res.json(USERS.users[req.params.id]);
});

app.get('/api/users/', function (req, res) {
console.log(USERS);
res.json(USERS);

});


My code for users.js:



module.exports = function () {

// Create User prototype and objects
var USERS = { users: [] };

function User(type, useremail, password) {
this.type = type;
this.useremail = useremail;
this.password = password;
}

var Bob = new User("rep", "bob@bob.com", "qwerty");
USERS.users.push(Bob);

var Helen = new User("rep", "helen@helen.com", "test");
USERS.users.push(Helen);

var Dominic = new User("customer", "dom@dom.com", "1234");
USERS.users.push(Dominic);

var James = new User("grower", "james@james.com", "pass1");
USERS.users.push(James);

};


I'm pretty new to this are but have been reading up alot on modules but still can't figure it out. Any suggestions on where I have gone wrong? or what I need to do to rectify the problem?


Note: Previously I did the same thing for including router into the server file using module.exports = function (app) { around my router and in my server as: require('./router/main')(app);


Aucun commentaire:

Enregistrer un commentaire