I was taking a look at NodeJS , when I came across this example:
module.exports = function(app){
var controllers = require('../controllers/controllers.js');
app.get('/libros', controllers.findAll);
}
The point is that this bit of code goes in the routes.js file . After testing it, I see that it works, but I don't quite understand why it can be used app
as a parameter when it hasn't even been imported.
The code you've posted looks a lot like in applications built with Express. You are simply passing an instance of Express already configured to a module where the routes that Express will handle are mapped.
Well, you don't need to directly import something to be able to use it . If you export a function from module B , then when you import said module you import the function and, like any function, you can pass parameters to it . There is no magic or anything in this, nor is it a special feature of CommonJS (library for modularization of JavaScript code adapted and implemented in Node.js), JavaScript just works like this. In Java for example, it is the same; in class A you import a class, create an object and you can pass this as a parameter in the method of another class.
On the other hand, that approach is not very flexible. It's best to map all routes using the router provided by Express:
This effectively separates your app into layers. Preferably, don't add handlers directly to routes because it's not the direct responsibility of the router; the responsibility lies with the handlers and it is good practice to have them in a separate layer so that you minimize dependencies between them.