五、模块系统

博客 分享
0 219
优雅殿下
优雅殿下 2022-03-06 09:56:12
悬赏:0 积分 收藏

五、模块系统

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

模块是Node.js 应用程序的基本组成部分,文件和模块是一一对应的。换言之,一个 Node.js 文件就是一个模块,

这个文件可能是JavaScript 代码、JSON 或者编译过的C/C++ 扩展。

一、 exports引入模块

模块的创建

首先,我们在项目中创建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 对象。

二、module.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


技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
个人开源代码链接,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee:https://gitee.com/mingliang_it
GitLab:https://gitlab.com/ITMingliang
进开发学习交流群:

posted @ 2022-03-06 09:30 農碼一生 阅读(0) 评论(0) 编辑 收藏 举报
回帖
    优雅殿下

    优雅殿下 (王者 段位)

    2018 积分 (2)粉丝 (47)源码

    小小码农,大大世界

     

    温馨提示

    亦奇源码

    最新会员