Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS, Express Structure and Require Confusion

This has been driving me crazy. I'm new to NodeJS. I love it so far but some things have been throwing me off. I was handed a very basic starting point to a node project and I'm unsure how to search google for this.

//myapp/server.js

var config  = require('./config');
var app     = express();
var api     = require('./app/routes/api')(app, express); // <-- this?

app.use('/', api);

var server = app.listen(3000, function () {
    console.log('\n============================');
    console.log(' Server Running on Port 3000  ');
    console.log('============================\n');
});

Then there's the api.js file that contains the routes.

//myapp/app/routes/api.js

var config   = require('../../config');
var mysql    = require('mysql');

module.exports = function(app, express) {

    var api = express.Router();

    api.all('/', function(req, res) {...});

    api.all('/route-two', function(req, res) {...});

    api.all('/another-route', function(req, res) {...});

    return api;
}

Ideally I'd like to break up what's going on here into a more organized structure but, I want to understand what I'm doing exactly.

The main thing that is confusing me is this line

var api = require('./app/routes/api')(app, express);

I was unaware that you can have ()() next to each other without a . or something joining them. Can someone explain what is happening?

Also what is the point of (app, express)? It appears that app and express are getting passed to the api part of the application so it's scope can be reached? Am I way off?

If there is a cleaner approach to this I would love to get some insight. I appreciate any thoughts.

Thanks!


EDIT To make sure I am understanding...

var api = require('require this file')(params available to this file);

Moving any requires from api.js to server.js then include those as parameters

var api = require('./app/routes/api')(config, app, express, mysql);

EDIT

After more helpful feedback from @AhmadAssaf @Gurbakhshish Singh and @guy mograbi

Modules I want to use in another file other than where they are require()ed should be passed in through the second set of ()

//.server.js
var config = require('./config');
var app    = express();                                          
var api    = require('./app/routes/api')(config, app, express); 
                                           |      |        |
                              _____________/______/________/
                             /      /      /
//.app/routes/api.js         |      |      |
module.exports = function(config, app, express) {

    var api = express.Router();

    // code to handle routes
}

Could be wrong with this part but based on what I think I am understanding.

//.server.js
var config = require('./config');
var app    = express();

var register = require('./app/routes/register')(config, app, express); 
var login    = require('./app/routes/login')(config, app, express); 
                                               |      |        |
                              _________________/______/________/
                             /      /      /
//.app/routes/login.js      |      |      |
module.exports = function(config, app, express) {...handle login...}

//.app/routes/register.js    
module.exports = function(config, app, express) {...handle registration...}    

etc. etc.

Hopefully my thinking is about right. I appreciate everyones help on this! :)

like image 931
Trozdol Avatar asked Aug 05 '15 19:08

Trozdol


People also ask

Why is require () used in NodeJS?

In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

What is require (' Express ') in NodeJS?

ExpressJS is a NodeJS module; express is the name of the module, and also the name we typically give to the variable we use to refer to its main function in code such as what you quoted. NodeJS provides the require function, whose job is to load modules and give you access to their exports.

Why is ExpressJS Unopinionated?

Express JS is minimal and unopinionated​Express uses less overhead in the core framework so that makes it minimal and a good choice for building out large web applications.

What is HTTP createServer in NodeJS?

The http. createServer() method turns your computer into an HTTP server. The http. createServer() method creates an HTTP Server object. The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.


1 Answers

So basically you have to understand few thing

  • module.exports wraps a Javascript object and export it to be used as a pluggable piece of code around a node.js application
  • The wrapped javascript object can be a JSON object, Javascript variable, function, etc.

What you have up there in the api module is a function that takes two parameters. When you require that module you want to pass some constructors to that function and thats the use of the second () after the module name in the first ()

requiring express once in your program and passing the variable around is more or less a singleton pattern. What you can also do is pass the config object as well to the api module instead of requiring it again :)

like image 101
AhmadAssaf Avatar answered Oct 23 '22 04:10

AhmadAssaf