Modular and distal base -Node specification CommonJS

Chapter 4 Node modular and standardized CommonJS

A few chapters earlier study, we basically mastered the basics of programming NodeJS, but we also intuitively found a problem, and when we learn before the browser programming JS, the difference is still very large; all JavaScript programming, why there is this difference? I wrote earlier cases of anti Apache server, used the built-fs module, used the moment modules, and these modules are not we write, are directly take over use, so we can not write your own module, how to write, what are the rules, if we wrote a module that can not be directly available to other programmers to use, how you should use?

Here Insert Picture Description

Electron desktop application framework cross-platform: https://electronjs.org/

4.1 CommonJS norms origin

JS performance capabilities depend on the performance of the API provided by the host environment, in the web1.0 era, W3C organization provides standardized support for the browser, in the web2.0 era, with the development of HTML5, more standard API appeared in browser, however, to develop a standard motionless in the back end of JS;

Proposed by the Mozilla engineer Kevin Dangoor in January 2009 called ServerJS specification; August 2009, it changed its name to * CommonJS, * to show the wider applicability of the API.

What I’m describing here is not a technical problem. It’s a matter of people getting together and making a decision to step forward and start building up something bigger and cooler together.

I'm not a technical problem described here. This is a people together, decided to step forward and start building something bigger cooler problem together.

–Kevin Dangoor

Here Insert Picture Description

4.2 CommonJS module specification

CommonJS very simple definition of modules, divided into:

1, the module reference:

Using the require()method of introducing the API module;

2, the module definition:

Use of such module exports the current object module data or methods;

There is also a module object module, which represents the module itself, module exports object has a property for data export;

In fact, exports target is module.exports references; exports === module.exports

3, the module identifier:

In fact, that is the module's filename, you must comply with the law named after a small hump rule, require()used when introduced . 或 ..at the beginning of the relative path

Path or /absolute path, you can not write the file extension is introduced;

Key Note : Scope methods and variables module only within the module, each module has an independent space, without disturbing each other;

CommonJS constructed module mechanism is introduced with no need to consider exporting our pollution or variable substitution problems, compared with the 命名空间mechanism, there is a huge gap;

4.3 Node achieve the CommonJS (Node modular)

Here Insert Picture Description

The above code is the custom module basic rule is this focus

4.4 loading module rules and the order

In CommonJS specification, a require()loading (introduced into) the module, the module identifier must be specified relative or absolute path module position, but in the implementation of the node, we can not specify module path; as: require('fs')、require('moment');

If you do not specify a path that is loaded kernel module or third-party modules, specify the load path in general is to load custom module;

No matter what the module is loaded, it is preferentially loaded from the cache:

When Node load module, this module is loaded if passed, will direct cached, Gaga will not load this module again referenced again in the future (ie: if a module is loaded twice, the module code will only be executed once)

The core module load order and third-party modules is:

First load the core module, the core content modules are installed in the node has compiled binary executable load speed of execution, after loading the cache, if there is no core module, load third-party modules

Third-party modules loaded rules:

  • First to find node_modules directory module Contents of the current file
  • If found, the directory to the directory to find the module name, such as: moment
  • If you find a moment directory, find the file in that directory package.json
  • If found package.json file, find the main attributes of the file
  • If the main attribute is found, the file corresponding to the attribute you get
  • If the directory to find the moment after,
    • No package.json
    • Or there is no main attribute package.json
    • Or have the main attribute, but the path does not exist points
    • The node will be the default directory to see what moment there is no index.js -> index.json-> index.node file
  • If the index can not find or can not find or can not find the moment node_modules
  • Then enter the parent directory to find node_moudles find (ibid rules)
  • If you can not find on a continued upward until the current file belongs to the root directory of the disk
  • If the disk directory shall have not found direct error

4.5 modular packaging case

Ideas:

1: server function -> apache

2: listens for requests -> Routing

3: The service request processing -> Controller

4: Get data (processing data) -> model

5: Display Data -> view

Case client rendering reconstruction

Modify http.js - server module

var http = require('http');
var router = require('./router');
var server = http.createServer();

router(server);

server.listen(8000,function(){
    console.log('欢迎来到node世界')
})

Add custom module router.js - routing module

var controller = require('./controller');

module.exports = function(server){
    server.on('request',function(req,res){
        var urls = req.url;
        if(urls == '/'){
            // 需要获取html文件中的内容
            // 响应给客户端
            // 业务层模块的调用
            controller.index(function(data){
                // 利用回调函数获取数据
                res.end(data);
            });
        }else if(urls == '/getnames'){
             // 业务层模块的调用 
            // 将请求对象及响应对象传入业务层方法,在业务层做http响应处理
            controller.getNames(req,res);
        }else{
            // 响应静态资源
            require('fs').readFile('.'+urls,function(err,data){
                res.end(data);
            })
        }
    })
}

contrllor.js - service module

var fs = require('fs');
var moment = require('moment');
module.exports = {
    index: function (callback) {
        // 返回静态页面
        fs.readFile('./index.html', 'utf8', function (err, data) {
            callback(data);
        })
        // console.log('index');
    },

    getNames: function (req, res) {
        // console.log('getnamesssss');
        fs.readdir('./', 'utf8', function (err, data) {
            var filearr = [];
            var cont = 0;
            for (var i = 0; i < data.length; i++) {
                // 2:
                (function (i) {
                    // 3:
                    fs.stat(data[i], function (err, stats) {
                        cont++;
                        // 获取文件名
                        // 问题:文件名为 undefined  
                        // 原因:在循环结束之后,函数才会被调用,而此时i已经被修改为最后的值
                        // 解决:在每次循环中形成一个独立的作用域保留i的值,
                        // 当异步函数调用时,获取到的是独立作用域中的i 
                        filearr[i] = {};
                        filearr[i].name = data[i];
                        // 获取文件的其他属性
                        filearr[i].type = stats.isFile();
                        filearr[i].size = stats.size;

                        // filearr[i].mtime = stats.mtime;
                        filearr[i].mtime = moment(stats.mtime).format("YYYY-MM-DD hh:mm:ss");
                        // 异步函数调用次数与文件数相等时,服务器作出响应并断开
                        if (cont == data.length) {
                            res.end(JSON.stringify(filearr));
                        }
                    })
                })(i);
            }
        })
    }
}

This document is a large number of reference books, documents, blog, manuals and other resources, the final interpretation of Wu Mingshi all;

Reference resource list:

https://nodejs.org/zh-cn/ node.js official website

http://nodejs.cn/ node.js Chinese network

"Layman's language Node.js" Spirit Park, People Post Press

https://en.wikipedia.org/wiki/CommonJS Wikipedia

"ECMAScript 6 Getting Started" (third edition) Ruan Yifeng forward, Electronic Industry Press

"You do not know JavaScript" (upper, middle and lower volumes) [US] Kyle Simpson, People Post Press

http://www.expressjs.com.cn/ express Chinese network

Released 1807 original articles · won praise 1929 · Views 170,000 +

Guess you like

Origin blog.csdn.net/weixin_42528266/article/details/105117329