Scope In NodeJS:
- Everything in node will be default to local scope
- Node manage modules with file model, all members in modules can access to it's scope variables but not other scope
- module.exports is used to public members for outside scope to access
- outside scope will access module's public member by require keyword
module.js
let someValue = 10;
function print(x) {
let valueToPrint = x * someValue;
console.log(x);
}
module.exports = {
someValue,
printToConsole: print
}
index.js
let myModule = require("module.js");
myModule.printToConsole(myModule.someValue); //result: 100
module.exports vs exports:
_module.exports _is an export-database that has global access in Node application. settings to modules.exports means add new records to that database for sharing between modules
exports by default is a reference to module.exports. it allows to access to member of module.exports but settings exports does mean change it's reference to another memory location, that cause it won't work as expected anymore
if there is any attached on module.exports , everything on exports will be ignored