简体   繁体   中英

Parsing JavaScript code in Node.js module

// ===============================================================================
// 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?

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM