Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Calling function in another file Node

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 81
    Comment on it

    It is always good practice to break your code into smaller files which are more meaningful as per the actions being performed in them. Splitting files into smaller one will require us to have some way by which we can call each other as required and event call functions or method being defined within them.

     

    Node help us in splitting files by making use "exports" . By default each file in node have their own scope within file only i.e variables or functions defined within a file is not accessible to outside world even tough it has been required in the given file. For example lets make a file of name sum.js having following content :

     

    var x = 5;
    var sum = function(value) {
      return value + x;
    };

     

    Other file wont be able to access variable x or sum function , this is because in node each file is a module and its scope is within same file only.

     

    Before moving ahead we would like to let you know how exactly modules are loaded in node :

     

    var sum = require('./sum');  // Here .js is optional node by default looks for .js,.json or .node extension.

     

    So until our module expose something var sum = require('./sum') won't be of much use . Thus in order to expose functions or variables node provide us with module.exports and export everything we want.

     

    var x = 5;
    var sum = function(value) {
      return value + x;
    };
    module.exports.x = x;
    module.exports.sum = sum;

     

    Now if we can use our sum module in some other file like this :

     

    var sum = require('./sum');
    console.log("Adding %d to 10 gives us %d", sum.x, sum.sum(10));

     

    Thus by making use of module.exports or exports we can make variables or functions as publically available thus allowing other file which will include it to make use of it.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: