美文网首页前端
Node.js--模块

Node.js--模块

作者: aix91 | 来源:发表于2019-01-04 21:26 被阅读0次

    1. 简介

    Node 封装了一些服务级别的API(文件处理,http...),这些api被封装成模块,可以直接在node.js 的代码中直接引入使用。

    2.常用的核心模块

    3. 模块的引入

    • node核心模块
      require([模块名]):加载并执行该模块;优先从缓存中加载,不会重复加载文件。
    var http = require("http");
    var server = http.createServer();
    
    • 第三方模块:如art-template,需要使用npm来下载。一个项目中只会有一个node-modules,存放在项目的根目录. 加载流程:
    1. 先在当前文件下找到node-modules目录,如果没有,则在上一级目录中找。
    2. 找到node-modules/art-template/package.json
    3. 找到package.json中main属性,main属性中就记录了art-template的入口模块
    4. 如果没有main属性,或者没有package.json 就使用该文件目录下的index.js.(如果没有index.js, 则会去上一级目录,非同级目录中查找node-modules,然后重复上面的加载规则)
    5. 然后使用加载这个第三方包
    6. 如果没有找到,则会报错: can not find module
    
    
    • 自己的模块: 引用时,注意加入路径

    4. exports 和module.exports

    模块化的编程,可以让node编译执行多个node文件;模块与模块之间的程序是相互独立的;使用exports(对象)可以将模块内的内容(属性,方法...)暴露出去。

    • 将模块内的属性,方法封装成一个新的对象,暴露出去
    exports.a = "hi"
    exports.b = function(){
        console.log("hi)
    }
    
    • 直接将模块类的方法,或者属性之际暴露出去
    module.exports = function(x,y){
      return x+y
    }
    

    5. 实例

    • 定义hello模块
    var foo = "bar";
    console.log(foo);
    exports.foo = foo;
    exports.hi = function () {
        console.log("hi");
    }
    
    • 定义demo模块
    var hi = require('./hello.js');
    hi.hi();
    console.log(hi.foo);
    
    • 执型demo模块node demo.js
    bar
    hi
    bar
    

    相关文章

      网友评论

        本文标题:Node.js--模块

        本文链接:https://www.haomeiwen.com/subject/xutlrqtx.html