I'm writing a larger App with duplex communication and database access via Node.js (with socket.io and mysql modules). Therefore I want to source out some files, so i don't have a huge server.js File (for example: a file for chat stuff, a file for database connection stuff, etc).
Is there a good method to arrange these files in my project? I am looking for something like getScript from jQuery, but I assume this won't worke, because it is an Ajax call, which doesn't make a lot sense on a Websocket-server, right?
Or is the best way to create own Modules!?
Yes create modules.
And if you want to pass values to a module you can make a function like:
var a, b, c;
var self = this;
//
// your module logic
//
exports.init = function(a, b, c) {
a = a;
b = b;
c = c;
return self;
}
This is the modular approach my favorite. Then you call like this from your code.
var myModule = require('./myModule').init('modular', 'is', 'fun');
Then you have the more traditional OOP
function ThisIsNotAclass(a,b,c) {
//
// your module logic
//
}
exports = function(a, b, c) {
return new ThisIsNotAclass(a,b,b);
}
Then you call like this from your code.
var myModule = require('./myModule')('modular', 'is more', 'fun');
I mainly use module.exports
. This is an example, core.js:
/**
* Initialize the core routes.
* @param app {Object} The app object.
*/
var core = function( app ) {
// CODE
};
/**
* Expose core.
* @type {Function}
*/
module.exports = core;
An here is app.js, at the end:
/**
* Routes.
*/
require("./controllers/core.js")(app);
I find this to be a good way of arranging files and logic.