用法:node模块都具备的方法(exports、module、require、__filename、__dirname)

 凡是玩弄nodejs的人,都明白,每一个模块都有exports、module、require、__filename、__dirname的方法

清楚了解方法的用法后,玩转node就等于清楚了日常讲话的内容

(function(exports,require,module,__filename,__dirname){
	//打印一出,所有模块的类型和值一目了然
	console.log("exports:",exports);
	console.log("__dirname:",__dirname);
	console.log("__filename:",__filename);	
	console.log("require:",require);
	console.log("module:",module);
	
})(exports,require,module,__filename,__dirname);

一、__filename

二、__dirname

三、exports

四、module

五、require

一、__filename

 *当前模块的文件路径:解析后的绝对路径

//输出当前的绝对路径
console.log(__filename);

扫描二维码关注公众号,回复: 2392276 查看本文章

二、__dirname

*存放当前模块的文件夹路径

//输出存放当前模块的文件夹名称
console.log(__dirname);

三、exports

*可以用来创建模块,是一个对于module.exports更加简短的引用形式。可以看出,module是exports的父亲,要是你是这么想的话,你会看不到明天的太阳,嗯~,暂且不论它们的区别。

//Untitled2.js
//官方模块http、fs、url用过没,要是没用过的话,你滚!
//量身为我而做的名片模块
exports.name="木人子韦一日尘";
exports.qq="2309485575";

  

//Untitiled1.js
//引用创建好的Untitled2模块
var myCard=require("./Untitled2");
console.log(myCard);

  

四、module

*基本包含了当前模块的全部信息,创建模块的事,module.exports也能办到,而且这才是真正的老大,exports不过是module的小弟,好东西都要上交给module大妈的

在有exports例子的前提下,修改Untitled2.js文件,Untitled1.js不变

我把exports和module.exports相互交换,你们亲自理解下

//Untitile2.js
//量身为我而做的名片模块 //module.exports赋值成类型为字符串,不为对象,不受exports创建子集影响 module.exports="我是不会变成对象的"; exports.name="木人子韦一日尘"; exports.qq="2309485575";

  

//Untitled2.js
//量身为我而做的名片模块
//module.exports类型想为对象,并创建子集,鸟都不鸟exports的请求
exports="我要变对象";
module.exports.name="木人子韦一日尘";
module.exports.qq="2309485575";

  

五、require

辛苦了require,把最简单的你晒在了最后,这话没毛病,白话讲,它主要是能够在当前模块引入其它模块,就是引入模块,用法好说好说。

/*require()括号里可填绝对路径或者相对路径,只要拟引入路径是指向后缀
名为js的文件,node老爷爷都会和蔼地认同“它是模块”,至于文件内容合不
合法,暂且不论*/
var myCard=require(__dirname+'/Untitled2.js');
/*如果是写相对路径的话,要注意一点,同级文件名称要改为./统计文件名称
,至于还有什么要注意的,暂且不论*/
console.log(myCard);

  

  

猜你喜欢

转载自www.cnblogs.com/murenziwei/p/9374293.html