模块封装器


¥The module wrapper

在执行模块代码之前,Node.js 将使用如下所示的函数封装器对其进行封装:

¥Before a module's code is executed, Node.js will wrap it with a function wrapper that looks like the following:

(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
}); 

通过这样做,Node.js 实现了以下几点:

¥By doing this, Node.js achieves a few things:

  • 它将顶层变量(使用 varconstlet 定义)保持在模块而不是全局对象的范围内。

    ¥It keeps top-level variables (defined with var, const, or let) scoped to the module rather than the global object.

  • 它有助于提供一些实际特定于模块的全局变量,例如:

    ¥It helps to provide some global-looking variables that are actually specific to the module, such as:

    • moduleexports 对象,实现者可以用来从模块中导出值。

      ¥The module and exports objects that the implementor can use to export values from the module.

    • 便利变量 __filename__dirname,包含模块的绝对文件名和目录路径。

      ¥The convenience variables __filename and __dirname, containing the module's absolute filename and directory path.