NodeJS module compiled Detailed

Module Compiler

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

function Module(id, parent){
	this.id = id;
	this.exports = {};
	this.parent = parent;
	if(parent && parent.children){
		parent.children.push(this);
	}
	this.filename = null;
	this.loaded = false;
	this.children = [];
}

Compile and execute the last phase of the introduction of the module file. After the target specific file, the Node module creates a new object, then compiled and loaded through the path. For different file extension, load it in the way are different, as follows.

.js文件。通过fs模块同步读取文件后编译执行。

.node文件。这是用C/C++编写的扩展文件,通过dlopen()方法加载最后的编译生成的文件。

.json文件。通过fs模块同步读取文件后,用JSON.parse()解析返回结果。

其余扩展名文件。它们都被当作.js文件解析。(因为node只能解析js文件,其他文件最后都会被转化成js文件,故当其余扩展名文件出现时,node无法识别,故将其认为是默认扩展名进行解析,即.js)

Each module will compile a successful path as an index file is cached on the Module._cache objects, introduced to improve the performance of the secondary.

Depending on the file name extension, node calls read different ways, such as: .json file calls is as follows:

Module._extensions['.json'] = function(module,filename){
	var content = NativeModule.require('fs').readFileSync(filename,'utf8');
	try{
		module.exports = JSON.parse(strinpBOM(cntent));
	}catch(err){
		err.message = filename + ':' + err.message;
		throw err;
	}
}

Which, Module._extensions will be assigned to require () the extensions property, so by accessing the require.extensions code loading may know already in the system. Write code to test:

//新建index.js文件
console.log(require.extensions);
//运行node index.js,输出
//[Object: null prototype] { '.js': [Function], '.json': [Function], '.node': [Function] }

If you want a custom extensions for special loading may be implemented in a similar require.extensions [ '. Ext'] manner. Early CoffeeScript document is by adding require.extensions [ '. Coffee'] to load the extension mode. But v0.10.6 release, no official encouragement to load custom extensions in this way, but expect first language or other file first and then compiled into a js file is loaded, the benefits of doing so is not a complicated compilation, such as load during the introduction of the implementation process node.

After determining the file extension, node will invoke a specific way to compile the file back to the caller after the execution.

Note: We all know CommonJS module specification, each module files are present in require、exports、module、_filename、_dirnamethese five variables do not know come from. If the process modules defined directly on the browser side, it is bound to the presence of contamination global variable, so its impossible.

In fact, during compilation, node js will get the contents of the file are packaged as follows:

(function(require、exports、module、_filename、_dirname){
	var math = require('math');
	exports.area = function(radius){
		return Math.PI * radius * radius;
	}
})

Have carried out such that each module acting between the paper separator. After the code package may () method is performed by native runInThisContext vm module, similar to the eval, but with a clear context, not global pollution, the object returns a function thereof. Finally, the properties of the current module exports the object, the require () method, Module1 (module object itself), and the complete file path and the file obtained in the positioning directory as an argument to this function () execution.

This is the reason why these variables and it can not be used in each module declaration. After the execution, the module exports property is returned to the caller. Any method Properties on exports can be invoked outside, but the remainder of the variables and the properties of the module can not be invoked directly.

At this point, require, exports, module process has been complete, and this is achieved CommonJS Node module specification.

JSON files compiled

Json file compiler compiler are three ways the easiest. After Node Synchronization module using fs JSON file to read the contents, calling the JSON.parse () method to get the object, and then assign it exports the object module, for external calls.

JSON file is useful when used as a project configuration file. If you define a JSON file as configuration, then do not go calling fs module asynchronous read and parse, direct calls require () can be introduced. In addition, you can also enjoy the convenience of a cache module, and does not affect the performance of the secondary introduction.

Here we compile modules mentioned refer to the file compiled module that is user-written.

Published 27 original articles · won praise 5 · Views 6117

Guess you like

Origin blog.csdn.net/systempause/article/details/104319453