为了让Node.js的文件可以相互调用,Node.js提供了一个简单的模块系统。
模块是Node.js 应用程序的基本组成部分,文件和模块是一一对应的。换言之,一个 Node.js 文件就是一个模块,
这个文件可能是JavaScript 代码、JSON 或者编译过的C/C++ 扩展。
模块的创建
首先,我们在项目中创建hello.js,代码如下:
exports.world = function() { console.log('Hello World');}exports.hi = function() { console.log('hi,nodejs');}hello.js通过exports将world和hi作为模块的访问接口,可以提供给外部加载调用。
模块的引入
在 Node.js 中,引入一个模块非常简单,如下我们创建一个 main.js 文件并引入 hello 模块,代码如下:
var hello = require('./hello');hello.world();hello.hi();以上实例中,代码 require('./hello') 引入了当前目录下的 hello.js 文件(./ 为当前目录,node.js 默认后缀为js)。
Node.js 提供了 exports 和 require 两个对象,其中 exports 是模块公开的接口,require 用于从外部获取一个模
块的接口,即所获取模块的 exports 对象。
模块的创建
如果将整个对象作为访问接口,我们在项目中创建hello.js,代码如下:
module.exports = function Hello() { var name; this.setName = function(theName) { name = theName; }; this.sayHello = function() { console.log('Hello ' + name); }; }或
function Hello() { var name; this.setName = function(theName) { name = theName; }; this.sayHello = function() { console.log('Hello ' + name); }; }module.exports = Hello;hello.js通过module.exports将Hello对象作为模块的访问接口,可以提供给外部加载调用。
模块的引入
在 Node.js 中,引入一个模块非常简单,如下我们创建一个 main.js 文件并引入 hello 模块,代码如下:
var Hello = require('./hello'); hello = new Hello(); hello.setName('刘德华'); hello.sayHello();exports返回模块函数,而module.exports返回模块本身。
exports 和 module.exports 的使用
(1)如果要对外暴露属性或方法,就用 exports 就行,要暴露对象(类似class,包含了很多属性和方法),就用
module.exports。
(2)不建议同时使用 exports 和 module.exports,如果先使用 exports 对外暴露属性或方法,再使用
module.exports 暴露对象,会使得 exports 上暴露的属性或者方法失效。
本文来自博客园,作者:農碼一生,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/15966387.html