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:

  1. With ./ require is going to check in the same directory
  2. With ../ require will look in parent directory
  3. We can also send an absolute path
  4. If we just send the name of the module without anything else, require will search by default in the node_modules directory. If it doesn't find it there, require will go up one directory until it finds it.

Sources: Inspired by Real Time Web Code School Course

Archive