node.js 中的 require() 是如何工作的? [英] How does require() in node.js work?
问题描述
我试过了:
// mod.js
var a = 1;
this.b = 2;
exports.c = 3;
// test.js
var mod = require('./mod.js');
console.log(mod.a); // undefined
console.log(mod.b); // 2
console.log(mod.c); // 3, so this === exports?
所以我认为 require() 可能是这样实现的:
So I image that require() may be implement like this:
var require = function (file) {
var exports = {};
var run = function (file) {
// include "file" here and run
};
run.apply(exports, [file]);
return exports;
}
是吗?请帮助我理解require(),或者我在哪里可以找到源代码.谢谢!
Is that right? Please help me to understand require(), or where can I find the source code. Thanks!
推荐答案
源代码是 此处.exports
/require
不是关键字,而是全局变量.您的主要脚本是 在 start 在一个函数中,该函数具有require等所有全局变量code>、
process
等在其上下文中.
Source code is here. exports
/require
are not keywords, but global variables. Your main script is wrapped before start in a function which has all the globals like require
, process
etc in its context.
请注意,虽然 module.js 本身使用的是 require()
,但这是一个不同的 require 函数,它是 定义在名为node.js"的文件中
Note that while module.js itself is using require()
, that's a different require function, and it is defined in the file called "node.js"
上面的副作用:在你的模块(不属于任何函数)中间有return"语句是完全没问题的,有效地注释掉"其余的代码
Side effect of above: it's perfectly fine to have "return" statement in the middle of your module (not belonging to any function), effectively "commenting out" rest of the code
这篇关于node.js 中的 require() 是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!