module.exports = {
method: function() {},
otherMethod: function() {},
};
const myModule = require('./myModule.js');
const method = myModule.method;
const otherMethod = myModule.otherMethod;
// OR:
const {method, otherMethod} = require('./myModule.js');
// foo.js
module.exports = 42;
// main.js
console.log(require("foo") === 42); // true
//2 ways of module.exports
// 1
function celsiusToFahrenheit(celsius) {
return celsius * (9/5) + 32;
}
module.exports.celsiusToFahrenheit = celsiusToFahrenheit;
//2
module.exports.fahrenheitToCelsius = function(fahrenheit) {
return (fahrenheit - 32) * (5/9);
};
require function returns exports of the require module.
module.exports is the returned object.
1)use module.exports to export single varibale e.g one class or one function
e.g module.exports= Calculator.
2)use exports to export multiple named variables
export.add = (a,b)=> a+b;
export.multiple=(a,b)=> a*b;
mycoolmodule/index.js
module.exports = "123";
routes/index.js
var mymodule = require('mycoolmodule')
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
console.log(mymodule);
});
/*will show 123 in the terminal*/
module.exports = router;
// foo.js
var exports = {}; // creates a new local variable called exports, and conflicts with
// living on module.exports
exports = {}; // does the same as above
module.exports = {}; // just works because its the "correct" exports
// bar.js
exports.foo = 42; // this does not create a new exports variable so it just works
// foo.js
console.log(this === module); // true