Reputation:
// ===============================================================================
// Auth
// ===============================================================================
const admin = require('firebase-admin'); //what happens if i move this line
admin.initializeApp(); //and this line
module.exports = function(app) {
//to this line
//and this line?
app.post('/login', function(req, res) {
const token = req.body.token;
console.log('token sent: ' + token);
admin
.auth()
.verifyIdToken(token)
.then(result => {
console.log('verifyIdToken result: ' + result);
});
res.send({ valid: 'havent programmed this yet' });
});
};
Let's say I'm working with the above code. I am curious why it still runs if I place the first lines of code:
const admin = require('firebase-admin');
admin.initializeApp();
from the outside of the anonymous function that module.exports to inside of it? I am so confused! Is this function looking outside of its module to grab this scope, and what is the difference in declaring this admin const from within module.exports rather than outside of it?
Upvotes: 0
Views: 55
Reputation: 609
To understand what is happening, you need to understand Javascript Closures and Module Pattern.
When the two lines are outside the module.exports, they are part of the global scope and hence visible
to your module. This is because variables defined outside any function, block, or module scope have global scope
inside the file.
When you move it inside the module, they become part of function/ module's scope and hence again visible
.
You can read this old but relevant article to get a better understanding. https://www.joezimjs.com/javascript/javascript-closures-and-the-module-pattern/
Upvotes: 2