require, module, exports. Cram or understand?

When we write nodejs code, we can’t write code in one file. That would be a nightmare for obvious reasons. So, we split our code into logical modules. We call upon those modules whenever we need them.

require is on the global object in nodejs. So, we can use it wherever we are.

Similarly, module is also on the global object in nodejs. It has exports object on it.

And this is the reason following code will work.

calculator.js

function counter(arr){
  return "The length of the array is " + arr.length;
}
function adder(a, b){
  return ​The sum of ${a} and ${b} is ${a+b}.`;
}
function multiplier(a, b){
  return ​The multiplication of ${a} and ${b} is ${a*b}.`;
}
var pi = 3.14;
module.exports = {
  counter: counter,
  adder: adder,
  multiplier: multiplier,
  pi: pi
};

main.js

var calculator = require('./calculator');

console.log(calculator.counter([1,2,3,4])); //The length of the array is 4
console.log(calculator.adder(1,2)); //The sum of 1 and 2 is 3.
console.log(calculator.multiplier(1,2)); //The multiplication of 1 and 2 is 3.
console.log(calculator.pi); //3.14

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s