Module Exports with Node.js
As an application begins to scale, the complexity can be reduced by modularizing your code in a way that it can be comprehended by other users. MVC frameworks like Backbone.js have already introduced concepts of Models, Collections and Views on the front end.
Understanding exports in Node.js
Node allows you to modularize your code at the backend by using module.exports
.
A file in Node is called a module. Functions and variables within a file cannot be accessed directly by using inheritence or dependency injection. However, it would be rather useful to expose the functionality of a file while keeping it modular at the same time.
The Module Object
Module is a reference to the object representing the current module or file. module.exports
is property that is accessible via the exports module-global.
module.exports
In order to export the functions and variables of a file with the function and a variable as shown below in example 1 we can use the module.exports
object.
Example 1
Now to load the mathFunctions.js module into another module we can use the require
statement. So for instance if we wanted to use add in another file we could simply require the file and assign it to a variable.
Example 2
In the example shown below, there is a user Model with a userSchema
that uses a userController and a Test that can be written for unit test purposes.