node.js中的require()如何工作? [英] How does require() in node.js work?

查看:164
本文介绍了node.js中的require()如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过这个:

// 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 不是关键字,而是全局变量。在包装 https://github.com/joyent/node/blob/6cbfcdad46d733bb04332063727e304e449dc86b/src/node.js#L794\"rel =noreferrer>在包含所有全局变量的函数中启动,如在其上下文中需要 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函数,它是已定义

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆