![](/img/trans.png)
[英]Best way to evaluate javascript source code module with node.js
[英]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' });
});
};
假设我正在使用上面的代码。 我很好奇为什么如果放置第一行代码,它仍然可以运行:
const admin = require('firebase-admin');
admin.initializeApp();
从module.exports到其内部的匿名函数的外部? 我感到很困惑! 此函数是否在其模块外部查找以获取此范围,并且从module.exports而不是外部声明此admin const有什么区别?
要了解正在发生的事情,您需要了解Javascript闭包和模块模式。
当这两行在module.exports之外时,它们是全局范围的一部分,因此对您的模块visible
。 这是因为在任何函数,块或模块范围之外定义的变量在文件内部都具有global scope
。
当您将其移动到模块内部时,它们将成为功能/模块范围的一部分,因此再次visible
。
您可以阅读这篇古老但相关的文章,以更好地理解。 https://www.joezimjs.com/javascript/javascript-closures-and-the-module-pattern/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.