over 8 years ago
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 :
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 :
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.
Now if we can use our sum module in some other file like this :
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)