Create our own module in Node.js
We have some functions that we want to be available through the require functionality in node.js. What does require returns? We use require when we want to reuse our code all throughtout our node.js application. Imagine we want to have a function which gives us a timestamp, after having a look at the Javascript Date Object we create the function we want to use from any point in our app in our file clock.js:
//clock.js
var whatTimeIsIt = function(){
console.log(new Date().toDateString());
}
exports = greetings;
As you can see, to define what we return when we require this function we have to use the exports object. Then in our application after requiring clock.js file, we can use it like this:
//app.js
var whatTimeIsIt = require('./clock');
whatTimeIsIt();
Another way is exporting a function into the exports object so when we write our require instruction later, we are going to get back an object (instead of a function), so we create export our function into the exports object like this:
//clock_object.js
exports.whatTimeIsIt = function(){
console.log(new Date().toDateString());
}
And then, we require our file, we get back an object and then we can call the function we exported in that object:
//app.js
var object = require('./clock_object');
object.whatTimeIsIt();
Notice that there is no need to assign what is return by require to an object, we can call require and call the function that it returns directly:
console.log(require('./clock_object').whatTimeIsIt();
How Require search for modules
Require will search for the modules like this:
- With ./
requireis going to check in the same directory - With ../
requirewill look in parent directory - We can also send an absolute path
- If we just send the name of the module without anything else,
requirewill search by default in thenode_modulesdirectory. If it doesn't find it there,requirewill go up one directory until it finds it.
Sources: Inspired by Real Time Web Code School Course
Archive
- 12 Feb 2014 Cómo usar Module.exports
- 11 Jan 2014 Primeros pasos con Pixi.js
- 10 Jan 2014 Create our own module in Node.js
- 05 Jan 2014 What is Titanium Alloy
- 04 Jan 2014 Entendiendo el metatag viewport
- 29 Dec 2013 First steps with Titanium
- 28 Dec 2013 Mocks en AngularJS $httpBackend
- 26 Dec 2013 Empezando con RequireJS
- 26 Dec 2013 Conociendo por fin Awk
- 26 Dec 2013 256 colores en VIM con Tmux