How to split NodeJS code in multiple files

In-case we are going to create a bigger application which may contain 100 or 1000 pages of source code.
It might be very difficult to write all the javascript code in just 1 file. So we should break our code into multiple files.

In NodeJS, there can be only one startup file like “index.js” or “app.js” or name of your choice. But there might be N number of dependent files which will allow our application for the routing, view and logic breakup in multiple files.

I am guess, you have a default file called “index.js” which is the startup file in your nodeJS application. Now create another file called “myConfig.js” and put some code inside that file.

You can write down following codes inside “myConfig.js”

1
2
3
4
5
module.exports = {
   sumTwoNumbers:function(){
      return 2+2; 
   };
};

OR you can write the same syntax in following manner as well

1
2
3
exports.sunTwoNumbers = function(){
  return 2+2; 
};

I am guessing you have kept “myConfig.js” in the root directory of your nodeJS application.

Now Open “index.js” and include the “myConfig.js” file or as a module.

var myConfig¬†= require(‘./myConfig.js’);

Remember i have not written require(‘myConfig.js‘), rather i have written require(‘./myConfig.js‘);

Now after including “myconfig.js” in your “index.js”, now you can call the function which is actually declared in “myConfig.js” file like the following way

myConfig.sumTwoNumbers();

So the final source code inside index.js will be following

1
2
var myConfig = require('./myConfig.js');
myConfig.sumTwoNumbers();

This way we can declare many function in separate file and call them in your required file. I should suggest you to go through the commonJS syntax documentation details to know more about it.

Even rather creating your own structure, try to follow nodeJS framework folder structure like sailJS or expressJS.

Happy coding :)