Modularity of the Nodejs

Source: Internet
Author: User

1. Introduction to Modularity in node. js
    • Why need modularity in node. js
        在后台开发语言中,比如Java、C#。他们都是隐含模块化的,Node.js默认帮我们提供了模块化这种机制。  在服务器端,我们想要使用底层的一些功能需要导入一些“包”来对其操作,比如操作文件、网络需要导入对应的包。其它语言中都是基于类来实现的模块化的思想,使用类来组织文件和文件之间的关联。  而Node.js中使用的是JavaScript语言,ECMAScript仅仅规定了基本的语法的书写,并没有规定文件之间关联,也就是说每个js文件之间是独立的,Node.js已经帮我们实现了js文件之间的关联(模块化)  Node.js中的模块化是基于CommonJS规范的
    • Limitations of JavaScript
      • No module system
      • The system provides fewer interfaces, such as: missing operation files, I/O flow and other commonly used interfaces
      • No standard interface, lack of unified interface such as Web server, database, etc.
      • Lack of management system mentor basic JavaScript application without the ability to automatically load and install dependencies
    • COMMONJS specification
      • node. JS was developed at the beginning of compliance with the COMMONJS specification
      • Make JavaScript like Java, Python, PHP and other languages have the basic ability to develop large-scale applications
      • The COMMONJS specification stipulates that each module has a separate scope
      • The COMMONJS specification stipulates that members published by each module use Module.exports or exports
      • With the modular system, node. JS provides a number of system modules: file, Buffer, I/O stream, socket, etc.
2. Node. JS Core Module
  • Import modules first before using core modules

  • Path module

    • Import module var path = require ("path");
    • basename () Get file name + suffix

          path.basename("/foo/hello/world/123.html")    //第二个参数,去掉获取的文件名中的相同部分    path.basename("c:/foo/hello/world/123.html",".html")
    • DirName () Get the Catalog

         
    • Extname () Gets the file name extension

        
    • Join () Merge path

           var p1 = "c://abc/xyz";     var p2 = "/123/456";     console.log(path.join(p1,p2));
    • Parse () converts the path to an object

        path.parse("c:\\home\\hello\\world\\123.html")  { root: ‘c:/‘,    dir: ‘c://home/hello/world‘,    base: ‘123.html‘,    ext: ‘.html‘,    name: ‘123‘ }
    • Format () Converts a path object to a path string

        var obj = { root: ‘c:\\‘,      dir: ‘c:\\home\\hello\\world‘,      base: ‘123.html‘,      ext: ‘.html‘,      name: ‘123‘ }  console.log(path.format(obj));
    • Delimiter environment variable delimiter, can cross platform under Windows is; Other platforms:

    • Path.sep path delimiter under Windows Yes \ Other next yes/
    • Isabsolute () is an absolute path
    • URL module

      • import module var url = require ("url");
      • Parse () converts the path of a string to an object

          var uri = "Http://www.baidu.com:8080/images/1.jpg?version=1.0&time=  1123#ABCD ";
           Console.log (Url.parse (URI));  
      • The
      • Format () Converts the Path object to a string

          var obj = {protocol: ' http: ', Slashes:true, Auth:null, Host: ' www.baidu.com:8080 ', Port: ' 8080 ', hostname: ' www.baidu.com ', hash: ' #abcd ', search: '? version =1.0&time=1123 ', query: ' version=1.0&time=1123 ', pathname: '/images/1.jpg ', path: '/images/1.jpg?ve  Rsion=1.0&time=1123 ', href: ' Http://www.baidu.com:8080/images/1.jpg?version=1.0&time=1123#abcd '};  var str = url.format (obj);
          Console.log (str);  
    • QueryString Module

      • Import module var querystring = require ("querystring");
      • Parse () parses the argument string into an object

          var obj = querystring.parse("version=1.0&time=123");  console.log(obj);
      • Stringify () Converts an object to a string
      • Escape () URL to encode
      • unescape () URL to decode
3. Where does the core module exist?
    • The core module is stored in the Node.exe, and when the Node.exe is running, the core module is loaded, and the require is loaded into memory
    • The source code can be found on GitHub, under the Lib folder
    • Faster execution of core modules
4. File module (custom module)
    • Definition File Module Add.js

                function add(a,b) {              return a + b;          }          //导出成员          exports.add = add;          //module.exports.add = add;
    • Using the file module main.js

                var obj = require("./add.js");          console.log(obj.add(5,6));
      • Note that the way to reference JS is different from the core module
              //使用相对于main.js 的方式查找add.js      var obj = require("./add.js");      var obj = require("./add");      //下面这种方式是引用核心模块或者包      //var obj = require("add");
5. Package
    The
    • COMMONJS Package specification gives programmers the standard for organizing modules, reducing the cost of communication

    • Package usage:

      • All modules placed in one folder (package name)
      • package put in current item The Node_modules folder in the
      • package defines a index.js (file name cannot be changed) export all modules
      • Reference package (contract greater than configuration)
    • Import Package Execution process Require ("Calc")

      • load Calc as core module, load not successful
      • automatically go to node_modules in the current directory to find a package with a file name of Calc
      • automatically go to Calc to find in Dex.js Export Module (exported module)
      • If index.js error is not found, Package.json config file is required if you want to change the export module
    • Package.js

name function
Name Package Name
Description Package Introduction, Introduction of package features
Version Version number, for version control
Keywords Keyword array for searching in NPM
Main Require first check this field when introducing a package
Dependencies Mark the list of packages that the current package depends on, and NPM will automatically load the dependent packages
Author Package author
License Open Source Licensing
{  "name": "calcpack",   "version": "1.0.0",  "description": "",  "main": "app.js",  "scripts": {   //可以通过npm run来执行    "test": "echo \"Error: no test specified\" && exit 1"  },  "keywords": [],  "author": "",  "license": "ISC"}
    • Standard ways to create packages

      • NPM init-y Automatically create Package.json
    • The structure of a standard package

name | function |---|---| Package.js | Package description File Bin | Store executable file lib | store JavaScript code DOC | store Document Test | Store Unit test Case Code README.MD | Documentation describing the role and usage of the package

    • Standard package execution Procedures
      • Loading Calcpack as a core module, loading is unsuccessful
      • Automatically go to the Node_modules in the current directory to find a package with the file name Calcpack
      • If there is package.json in Calcpack, and the value of the main property is specified, the. JS module specified by main is loaded first (export module)
      • If there is no Package.json, or the main attribute is not specified, automatically go to Calcpack to find the Index.js exit module (exported module)
      • If the index.js error is not found
6. Release the package
    • Publish package to NPM website  https://www.npmjs.com/

      • Create a package, set Package.json
      • Register account in Npmjs
      • execute at the root of the package
        • NPM adduser Add user information for the release package, sign in to the Web site
        • npm publish release or update package Package.json Be sure to specify maintain ers:[{
            "name": "Nllcode", "email": "[email protected]"  
          }]
        • NPM cache Clear Clears NPM Cache, used to publish a new version with the same version number
        • NPM unpublish @  Delete published version code NPM unpublish [email protected]
    • Error

      • only Admin can publish this module
      • fix: Modify source npm config set Regis try http://registry.npmjs.org
    • Install package

      • Installing from the Network
        • Current directory install NPM install package name
        • Global Install NPM Install package name-G
      • Path to locally installed NPM install package
      • Uninstall Package NPM Uninstall package name
    • require () Load rule

      • Load module or package from cache first
      • Load the file module to use a relative path. /
      • The file module can be loaded without the suffix name if the suffix name is not written in the order of. js >. node >. JSON
      • Loading the JSON file, it is recommended to write the suffix. JSON
      • Load core modules or packages, do not write paths and suffixes
      • Module.paths loading the node_modules, load it in the order of this array

Modularity of the Nodejs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.