Error encountering NodeJS module

3

I'm following a book of NodeJS and it's giving the following error:

Error: Cannot find module './app/routes/home'

I have reviewed several times and found nothing wrong, here is the code:

Express.js

// config/express.js
var express = require('express');
var home = require('./app/routes/home');
module.exports = function () {
    var app = express();
    // variável de ambiente
    app.set('port', 3000);

    // middleware responsavel por tornar acessivel tudo dentro da pasta public, recebe como parametro a pasta public
    app.use(express.static('./public'));
    //No Express, template engines são confiurados em variáveis de ambiente
    //view engine utilizada é ejs.  
    app.set('view engine', 'ejs');
    //definimos o diretório onde fiarão nossas views
    app.set('views', './app/views');
    home(app);

    return app;
};

Route:

// app/routes/home.js

var controller = require('./app/controller/home');

module.exports = function (app) {
    app.get('/index', controller.index);
    app.get('/', controller.index);

}

Controller:

// app/controllers/home.js
module.exports = function () {
    var controller = {};
    controller.index = function (req, res) {
        res.render('index', { nome: 'Express' });
    };
    return controller;
}

And finally the server.js

// server.js
var http = require('http');
var app = require('./config/express')();
http.createServer(app).listen(app.get('port'), function () {
    console.log('Express Server escutando na porta ' +
        app.get('port'));
});

Where can I be wrong?

Directory structure :

    
asked by anonymous 24.08.2015 / 22:36

2 answers

3

I usually use console.log(__dirname); when I'm not sure what directory the file is.

In your case you have an error in the directory name controllers or in the path that points var controller = require('./app/controller/home'); . It repairs% w /% that sets them apart.

Fixing this uses s to get down a directory level relative to the one where the file is. Respectfully:

var home = require('../app/routes/home');

and

var controller = require('../controller/home');
    
24.08.2015 / 23:10
0

The problem is that only one directory level has gone down and the desired directory is two levels down. instead of:

../app/controllers/home

Use:

../../app/controllers/home
    
03.09.2016 / 16:38