美文网首页程序员
10分钟搞懂 Node.js 的模块概念

10分钟搞懂 Node.js 的模块概念

作者: 某尤 | 来源:发表于2017-06-03 19:14 被阅读115次

    什么是模块?

    Node.js 通过实现 CommonJS 的 Modules 标准引入了模块(module)概念。在 Node.js 中一个文件就是一个模块。这个文件可以是 JavaScript 代码、JSON 文件、编译过的C/C++扩展。

    Node.js 的模块分为两类,一类是原生模块,一类是文件模块。原生模块可以直接通过 require 去导入。文件模块又可以分为三种:

    .js,通过 fs 模块同步读取 js 文件并编译执行。
    .node,通过 C/C++ 编写的 Addon。通过 dlopen 方法进行加载。
    .json, 读取文件,调用 JSON.parse 解析加载。

    Node.js 提供了 exportsrequire 两个对象,用于模块的导出和导入。

    如何导入、导出模块?

    show me the code :)

    foo.js:

    exports.foo = 'bar' // 导出对象
    

    app.js:

    var x = require('./foo.js'); // 导入 foo.js 模块, .js写或不写都行
    console.log(x.foo)
    

    运行 app.js:node app.js,得到:bar

    思考:foo.js 的文件可以写成这样吗?

    exports = { foo : 'bar' }
    

    答案是不能。exports 对象实际上是引用了 module.exports 对象的。如果用上面这种写法会使这个引用被破坏。

    对一个变量赋值会使其指向被赋值的对象。

    let foo = { title: 'ue900s' }
    let bar = foo;
    
    console.log(foo); // { title: 'ue900s' } 
    console.log(bar); // { title: 'ue900s' }
    
    bar.title = 'ie80'; 
    console.log(foo); // { title: 'ie80' }
    console.log(bar); // { title: 'ie80' }
    
    bar = {}; // 使 bar 指向一个空对象
    console.log(foo); // { title: 'ie80' }
    console.log(bar); // {}
    

    更好的写法:

    exports = module.exports = { foo: 'bar' };
    

    这实际上等价于:

    module.exports = { foo: 'bar' };
    exports = module.exports
    

    exports 和 module.exports 的区别

    1. module.exports 初始值为一个空对象 {}
    2. exports 是指向的 module.exports 的引用
    3. require() 返回的是 module.exports 而不是 exports

    相关文章

      网友评论

        本文标题:10分钟搞懂 Node.js 的模块概念

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