Sunday, June 18, 2017

Load modules in Node.js

When we create modules in Node.js, we can use "module.exports" or "exports" objects. However, I didn't understand the difference of them. In this article I have sorted out when to use each object.
Note: I don't mention the detailed difference of the two in this article, you can find it in the link described below.

Which to use, "module.exports" or "exportsx"?

Use "module.exports" to export single class function or object.

class MyClass {
    ...
}
module.exports = MyClass;

Use "exports" to export multiple functions or objects.

function myFunc1 {
    ...
}
function myFunc2 {
    ...
}
exports.myFunc1 = myFunc1;
exports.myFunc2 = myFunc2;

* "module.exports" can also be used, but using "exports" is simpler.

module.exports = {
    myFunc1: myFunc1,
    myFunc2: myFunc1
}

The behaivior when executing "require" mutilple times.

The script loaded by "require" is evaluatted only the first time and "require" returns cached object from the second time.

  • module.js
var _var = Math.random();
function func() {
    console.log(`module.js - func : _var=${_var}`)
}
exports.func = func;
  • main.js
const module1 = require('./module.js')
const module2 = require('./module.js')
module1.func()
module2.func()
  • Result
module.js - func : _var=0.7381836391077983
module.js - func : _var=0.7381836391077983

Reference

No comments:

Post a Comment