nodeJS基础:模块系统

1. node JS 模块介绍

为了让Node.js的文件可以相互调用,Node.js提供了一个简单的模块系统。

模块是Node.js 应用程序的基本组成部分,文件和模块是一一对应的。换言之,一个 Node.js 文件就是一个模块,这个文件可能是JavaScript 代码、JSON 或者编译过的C/C++ 扩展。

2. 创建模块

Node.js 提供了exports 和 require 两个对象,其中 exports 是模块公开的接口,require 用于从外部获取一个模块的接口,即所获取模块的 exports 对象。 

实例:备注,在以下实例中 main.js 与 hello.js 都是处于同一文件夹下

// main.js

// 1. require('./hello') 引入了当前目录下的hello.js文件(./ 为当前目录,node.js默认后缀为js)。
var hello = require("./hello");

//2. 使用模块
hello.hello("gaoxiong")
// hello.js

// 写法1
module.exports.hello = function(name){
    console.log(name);
};

// 写法2
exports.hello = function(name){
    console.log(name);
}

// 写法1,2都是可以的

在终端执行:node main.js 会打印 gaoxiong,不知道你有没有留意上面,在调用模块方法时时通过 hello.hello(params);这是为什么呢?我们在hello.js中 暴露出的不是一个函数吗?错了!!!实际上这就牵扯到了以下暴露方法的区别

  • exports:只能暴露出一个对象,不管你暴露出什么,它返回的总是一个对象,对象中包含你所要暴露的信息
  • module.exports能暴露出任意数据类型

验证:

//第一种情况
//
main.js var hello = require("./hello"); console.log(hello); // hello.js exports.string = "fdfffd"; conosle.log 结果: { string: 'fdfffd' }
// main.js
var hello = require("./hello");
console.log(hello);

// hello.js
module.exports.string = "fdfffd";

// console.log()结果
{ string: 'fdfffd'}
// main.js
var hello = require("./hello");
console.log(hello);

// hello.js
module.exports = "fdfffd";

//conosle.log() 结果
fdfffd
// main.js
var hello = require("./hello");
console.log(hello);

// hello.js
exports = "fdfffd";
 
// conosle.log()结果 => 一个空对象

{}

对象上面四个情况可以得出:

module.exports.[name] = [xxx]  与 exports.[name]  都是返回一个对象 对象中有 name 属性

而module.exports = [xxx]  返回实际的数据类型    而 exports = [xxx]  返回一个空对象:不起作用的空对象

 

 

原文地址:https://www.cnblogs.com/gao-xiong/p/6005773.html