user4209821
user4209821

Reputation:

Put additional logic in server.js file

I've the server.js file which is the starting point of my node application and also responsible to invoke 3 different functions( this functions are invoked just once when the server is up , function like create childProcess ,validaton etc ) which is OK.

My questions is

  1. Should I put this logic (3 functions below) in different file in the controller folder or its OK to keep it on the server.js file(SOC?)?
  2. If I put those functions calls in different file (in the controller folder) should I invoke those functions via event(like event serverIsUp...) Example for this approach will be very helpful

The server.js look like following(in short...)

http.createServer(app).listen(app.get('port'), function (err) {
    if (err) {
        console.error(err);
    } else {
        console.log('server listening on port ' + app.get('port'));
    }
});

...
//Here it the function which is called when the server is up and running 
childProcess.createProcess() ;

fileParser.parse();

invokeValidations();

Upvotes: 2

Views: 94

Answers (1)

michelem
michelem

Reputation: 14590

You can create a new file (or several ones for each function) and export/require the function:

In newfile.js you export the function

exports.invokeValidations = function () {
    // Do something
}

In server.js you require the file and invoke the function

myFunctions = require('./newfile.js');

myFunctions.invokeValidations();

And for you should or not, that's up to you, if functions increase I would recommend to put them into separate files to keep stuff organised.

EDIT:

To use event emitter you should create your own emitter:

emitter.js:

var EventEmitter = require('events').EventEmitter;
var localEmitter = new EventEmitter();

module.exports = localEmitter;

Then you should require it in server.js and in your module.js

server.js:

var myEmitter = require('./emitter');
    myModule = require('./module');

myEmitter.on('boot', function(){
    console.log('hello world !');
});


myModule.invokeValidations();

module.js:

var myEmitter = require('./emitter');

exports.invokeValidations = function () {
   myEmitter.emit('boot');
   // Do something
};

And you are done

Upvotes: 1

Related Questions