Error finding Nodejs module

Asked

Viewed 2,055 times

3

I’m following a book by NodeJS and is making the following mistake:

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

I’ve gone over and over and found nothing wrong, here’s 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 last but not least the.js server

// 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 missing?

Directory structureinserir a descrição da imagem aqui:

  • Could be some problem in the EJS ?

  • var controller = require('./app/controller/home'); there’s no one missing s in controller?

  • I also thought at first, but in the book is without the s but even so I put and the error persists.

2 answers

3


I use to console.log(__dirname); when I’m not sure which directory the file is.

In your case you have an error in the board’s name controllers or the path you point to var controller = require('./app/controller/home');. Look at the s that differentiates them.

Fixing it uses ../ to lower a directory level relative to the one the file is in. Respectively:

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

and

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

0

The problem is that only one directory level has been lowered and the intended directory is two levels below. instead of:

../app/controllers/home

Use:

../../app/controllers/home

Browser other questions tagged

You are not signed in. Login or sign up in order to post.