Tutorial: Creating Node.js modules

Node.js Modules

In this short tutorial I’m going to explain how you can create your own modules in Node.js, as everyone knows we cannot keep our entire code in only one js file, as your application grows it’ll be almost impossible for you to maintain your code, for this reason it’s essential that we separate our code in modules, this way it’ll hopefully always be organized and easy to maintain.

Node.js makes it very easy for us to create custom modules, let’s suppose we need to put 2 functions in a separated module, we just need to create a new js file like this:

newModule.js

1
2
3
4
5
6
7
exports.function1 = function(){
	console.log('Function 1');
}
 
exports.function2 = function(){
	console.log('Function 2');
}

As you can see it’s a very straightforward code, all I did was to create 2 functions and add them to module.exports, unless you don’t want your functions to be visible to other modules it’s very important that you add them to exports.

Now you can require this new module in another module as follows:

app.js

1
2
3
4
var newModule = require('./newModule');
 
newModule.function1();
newModule.function2();

When requiring a module you have to pass its full path to the require function, in this example I’m assuming that the 2 js files are in the same folder. After requiring your module you’re done! Now this app.js file has access to all the functions you’ve exported from your new module.

Recommended for you

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>