在节点中如何需要()。js的工作吗?

时间:2021-05-19 22:28:06

I tried this:

我试着这样的:

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

So I image that require() may be implement like this:

因此我认为require()可以实现如下:

var require = function (file) {
    var exports = {};
    var run = function (file) {
        // include "file" here and run
    };
    run.apply(exports, [file]);
    return exports;
}

Is that right? Please help me to understand require(), or where can I find the source code. Thanks!

是这样吗?请帮助我理解需要(),或者在哪里可以找到源代码。谢谢!

4 个解决方案

#1


45  

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.

源代码在这里。导出/需求不是关键字,而是全局变量。在开始之前,您的主脚本被包装在一个函数中,该函数在上下文中包含了所有全局变量,如require、process等等。

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"

注意,尽管模块。js本身使用require(),这是一个不同的要求函数,它在名为“node.js”的文件中定义。

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

上面的副作用:在模块中间有“return”语句(不属于任何函数)是很好的,可以有效地“注释掉”代码的其余部分

#2


8  

Andrey showed the source code, but if you also wonder how to use it, the easy and simple explanation is here (http://nodejs.org/api/modules.html).

Andrey展示了源代码,但是如果您也想知道如何使用它,这里有简单的解释(http://nodejs.org/api/modules.html)。

These were two good examples for me.

这是两个很好的例子。

//foo.js, multiple methods
var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is ' + circle.area(4));

//circle.js
var PI = Math.PI;
exports.area = function (r) {
  return PI * r * r;
};
exports.circumference = function (r) {
  return 2 * PI * r;
};

//bar.js
var square = require('./square.js');
var mySquare = square(2);
console.log('The area of my square is ' + mySquare.area());

//square.js, single method
module.exports = function(width) {
  return {
    area: function() {
      return width * width;
    }
  };
}

My favourite pattern is

我最喜欢的模式是

(function (controller) {

  controller.init = function (app) {

    app.get("/", function (req, res) {
        res.render("index", {});
    });

  };
})(module.exports);

#3


3  

var mod = require('./mod.js');

The require is a function that takes one argument called path, in this case the path is ./mod.js

require是一个函数,它接受一个名为path的参数,在本例中路径是./mod.js

when the require is invoked, a sequences of tasks are happened:

在调用需求时,会发生一系列任务:

  1. call Module.prototype.require function declared in lib/module.js which assert that the path exists and was a string

    Module.prototype打电话。需要在lib/module中声明的函数。它断言路径存在并且是一个字符串

  2. call Module._load which is a function in lib/module.js that resolve the file through Module._resolveFilename(request, parent, isMain),

    调用模块。_load是lib/module中的函数。通过模块解析文件的js。_resolveFilename(请求、父母isMain),

  3. the Module._resolveFilename function is called and checks if the module is native (The native modules are returned by NativeModule function defined in lib/internal/bootstrap_node.js), if yes it will return the module else it checks the number of characters of the parh (Must 2 character at least) and some characters (the path must started by ./) via Module._resolveLookupPaths function defined in defined in lib/internal/bootstrap_node.js
  4. 模块。_resolveFilename本机函数被调用,并检查其是否模块(本机NativeModule返回的模块函数定义在lib /内部/ bootstrap_node.js),如果是它将返回其他模块它检查parh的字符数(必须至少2个字符)和一些字符(路径必须开始了。/)通过模块。_resolvelookupp誓言函数在lib/internal/bootstrap_node.js中定义
  5. check the directory that contains the file
  6. 检查包含该文件的目录
  7. If the path contains an extension (in our example yes: mod.js), the basename function defined in lib/path.js checks that the extension is "js"
  8. 如果路径包含一个扩展(在我们的示例yes: mod.js中),那么在lib/path中定义的basename函数。js检查扩展名是否为“js”
  9. then it will create a new module for the file given in argument var module = new Module(filename, parent);
  10. 然后为参数var模块= new模块中给定的文件创建一个新模块(文件名,父);
  11. the content will be compiled via v8 through the function NativeModule.prototype.compile defined in lib/internal/bootstrap_node.js
  12. 内容将通过v8通过函数nativemodu .prototype.compile,后者在lib/internal/bootstrap_node.js中定义
  13. the NativeModule.wrap defined in lib/internal/bootstrap_node.js takes the javascript content compiled of mod.js and wraps it : It wraps it in some other code that makes all this work. So the code you've written in mod.js is wrapped in a function expression. that means everything you write in node is run in V8
  14. NativeModule。包中定义的lib /内部/ bootstrap_node。js接受由mod.js编译的javascript内容,并将其封装:它将其封装在其他代码中,从而使所有这些工作正常进行。因此,在mod.js中编写的代码被封装在一个函数表达式中。这意味着在node中编写的所有内容都在V8中运行
  15. a module.exports is what's returned
  16. 一个模块。出口是回来了

#4


-8  

The source is available here next to the downloads : http://nodejs.org/ exports/require are keywords, I don't think they are coded in javascript directly. Node is coded in C++ , javascript is just a scripting shell around the C++ core.

这个源代码可以在下载的旁边找到:http://nodejs.org/ exports/require都是关键字,我认为它们不是直接用javascript编写的。Node是用c++编写的,javascript只是围绕c++核心编写的一个脚本shell。

#1


45  

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.

源代码在这里。导出/需求不是关键字,而是全局变量。在开始之前,您的主脚本被包装在一个函数中,该函数在上下文中包含了所有全局变量,如require、process等等。

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"

注意,尽管模块。js本身使用require(),这是一个不同的要求函数,它在名为“node.js”的文件中定义。

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

上面的副作用:在模块中间有“return”语句(不属于任何函数)是很好的,可以有效地“注释掉”代码的其余部分

#2


8  

Andrey showed the source code, but if you also wonder how to use it, the easy and simple explanation is here (http://nodejs.org/api/modules.html).

Andrey展示了源代码,但是如果您也想知道如何使用它,这里有简单的解释(http://nodejs.org/api/modules.html)。

These were two good examples for me.

这是两个很好的例子。

//foo.js, multiple methods
var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is ' + circle.area(4));

//circle.js
var PI = Math.PI;
exports.area = function (r) {
  return PI * r * r;
};
exports.circumference = function (r) {
  return 2 * PI * r;
};

//bar.js
var square = require('./square.js');
var mySquare = square(2);
console.log('The area of my square is ' + mySquare.area());

//square.js, single method
module.exports = function(width) {
  return {
    area: function() {
      return width * width;
    }
  };
}

My favourite pattern is

我最喜欢的模式是

(function (controller) {

  controller.init = function (app) {

    app.get("/", function (req, res) {
        res.render("index", {});
    });

  };
})(module.exports);

#3


3  

var mod = require('./mod.js');

The require is a function that takes one argument called path, in this case the path is ./mod.js

require是一个函数,它接受一个名为path的参数,在本例中路径是./mod.js

when the require is invoked, a sequences of tasks are happened:

在调用需求时,会发生一系列任务:

  1. call Module.prototype.require function declared in lib/module.js which assert that the path exists and was a string

    Module.prototype打电话。需要在lib/module中声明的函数。它断言路径存在并且是一个字符串

  2. call Module._load which is a function in lib/module.js that resolve the file through Module._resolveFilename(request, parent, isMain),

    调用模块。_load是lib/module中的函数。通过模块解析文件的js。_resolveFilename(请求、父母isMain),

  3. the Module._resolveFilename function is called and checks if the module is native (The native modules are returned by NativeModule function defined in lib/internal/bootstrap_node.js), if yes it will return the module else it checks the number of characters of the parh (Must 2 character at least) and some characters (the path must started by ./) via Module._resolveLookupPaths function defined in defined in lib/internal/bootstrap_node.js
  4. 模块。_resolveFilename本机函数被调用,并检查其是否模块(本机NativeModule返回的模块函数定义在lib /内部/ bootstrap_node.js),如果是它将返回其他模块它检查parh的字符数(必须至少2个字符)和一些字符(路径必须开始了。/)通过模块。_resolvelookupp誓言函数在lib/internal/bootstrap_node.js中定义
  5. check the directory that contains the file
  6. 检查包含该文件的目录
  7. If the path contains an extension (in our example yes: mod.js), the basename function defined in lib/path.js checks that the extension is "js"
  8. 如果路径包含一个扩展(在我们的示例yes: mod.js中),那么在lib/path中定义的basename函数。js检查扩展名是否为“js”
  9. then it will create a new module for the file given in argument var module = new Module(filename, parent);
  10. 然后为参数var模块= new模块中给定的文件创建一个新模块(文件名,父);
  11. the content will be compiled via v8 through the function NativeModule.prototype.compile defined in lib/internal/bootstrap_node.js
  12. 内容将通过v8通过函数nativemodu .prototype.compile,后者在lib/internal/bootstrap_node.js中定义
  13. the NativeModule.wrap defined in lib/internal/bootstrap_node.js takes the javascript content compiled of mod.js and wraps it : It wraps it in some other code that makes all this work. So the code you've written in mod.js is wrapped in a function expression. that means everything you write in node is run in V8
  14. NativeModule。包中定义的lib /内部/ bootstrap_node。js接受由mod.js编译的javascript内容,并将其封装:它将其封装在其他代码中,从而使所有这些工作正常进行。因此,在mod.js中编写的代码被封装在一个函数表达式中。这意味着在node中编写的所有内容都在V8中运行
  15. a module.exports is what's returned
  16. 一个模块。出口是回来了

#4


-8  

The source is available here next to the downloads : http://nodejs.org/ exports/require are keywords, I don't think they are coded in javascript directly. Node is coded in C++ , javascript is just a scripting shell around the C++ core.

这个源代码可以在下载的旁边找到:http://nodejs.org/ exports/require都是关键字,我认为它们不是直接用javascript编写的。Node是用c++编写的,javascript只是围绕c++核心编写的一个脚本shell。