Node.js 提供了一个简单的模块系统,这可以让Node.js的文件可以相互调用。一个Node.js文件就是一个模块,这个文件很可能是JS代码或者JSON。
引入模块
创建一个文件引入hello.js模块
// 引入hello.js文件
const print = require('./hello');
print(); // 直接调用函数
另一个文件:
// hello.js
function Hello() {
console.log('Hello world!');
}
//导出函数hello
module.exports = Hello;
当然也可以引入多个函数,这就需要我们在exports的时候将两个函数分别作为对象的属性导出,因此在另一个文件中导入时,可以通过对象的属性名来调用相应的函数。写法与之前不同的是,作为属性导出需要加符号“{}”。
// me.js
function tietie() {
console.log('贴贴。。。');
}
function nienie() {
console.log('捏捏。。。');
}
module.exports = {
tietie,
nienie
};
引入模块:
const me = require ('./me.js');
me.tietie();
me.nienie();