Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Modules compiled

In Node, each file module is an object, defined as follows:

function Module(id,parent){
    this.id = id;
    this.exports = {};
    this.parent = parent;
    if(parent && parent.children){
        parent.children.push(this);
    }
    this.filenane = null;
    this.loaded = false; 
    this.chilaren = [];
}
Copy the code

Compilation and execution are the final stages in introducing a file module. Once the file is located, Node creates a new module object, which it loads and compiles according to the path. The loading method varies for different file extensions, as shown below

  • Js file. Read files synchronously through fs module and compile and execute.
  • The node file. This is an extension file written in C/C++ that loads the file generated by the final compilation through the dlopen() method
  • Json file. After reading the file synchronously through the FS module, the returned result is parsed with json.parse ()
  • Other extension files. They are all loaded as JS files

Each compiled Module will cache its file path as an index on the module._cache object to improve the performance of secondary imports. Depending on the file extension, Node invokes different read methods, such as. Json files:

Module._extensions['. Json "] = function(Module,filenane){var content = nativemodule.require (fs"). ReadfileSync (filename, "utf8"); try { module.exports*ISON.parse(stripB0M(content)); } catch (err) { err.message = filename + ': ' + err.message throw err }Copy the code

Compilation of JavaScript modules

Back to the CommonJS module specification, we know that each module file contains three variables: require, exports, module, but they are not defined in the module file. Where do they come from? Even in the Node API documentation, we know that the _filename and _dirname variables exist in each module. Where did they come from? If we put the process of defining modules directly on the browser side, we can pollute global variables. In fact, Node wraps the contents of the retrieved JavaScript file during compilation. Added in the header

(function(exports, require,module, _filename, _dirname){\n, added \n])Copy the code

A normal JavaScript file would be wrapped like this:

Function (exports, require,module, _filename, _dirname){var math = require('math'); function (exports, require,module, _filename, _dirname){var math = require('math'); exports.area = function(radius){ return Math.PI * radius * radius; }}Copy the code

This provides scope isolation between each module file.

C /C++ module compilation

Compilation of JSON files