首页 > Web开发 > 详细

NodeJS模块的使用

时间:2016-08-06 11:22:55      阅读:266      评论:0      收藏:0      [点我收藏+]

在NodeJS中,每个js文件就是一个模块,而文件路径就是模块名, 在编写每个模块时,都有require、exports、module三个预先定义好的变量可供使用。

 

require函数用于在当前模块中加载和使用别的模块,其中js扩展名可省略,require多次不会重复初始化,如果传递给require函数的是NodeJS内置模块名称,不做路径解析,require(‘express‘);

exports对象是当前模块的导出对象,用于导出模块公有方法和属性。别的模块通过require函数使用当前模块时得到的就是当前模块的exports对象。

导入导出结合使用:

hello.js

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


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

//写法3
// this.hello=function(){
//     console.log(‘hello world‘);
// }

test.js

var me=require(‘./hello.js‘);
me.hello();

技术分享

 还有一种写法:

hello.js

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

main.js

var me=require(./hello.js);
me();

 

module通过module对象可以访问到当前模块的一些相关信息,但最多的用途是替换当前模块的导出对象。

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


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

//写法3
// this.hello=function(){
//     console.log(‘hello world‘);
// }
mordel.exports=function(){
    console.log(‘bad world‘);
}

技术分享

NodeJS模块的使用

原文:http://www.cnblogs.com/tinyphp/p/4922920.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!