NodeJS模块的使用

时间:2023-03-09 13:28:32
NodeJS模块的使用

在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();

NodeJS模块的使用

还有一种写法:

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模块的使用