Node.js内置多个模块,也可以使用第三方模块,今天学习一下如何使用自己定义的模块
在同级目录下定义两个js文件
第一个:custom1.js
"use strict";
function hello() {
console.log("Hello world!!");
}
//将自定义的一个函数hello抛出到外部
module.exports = hello;
扫描二维码关注公众号,回复:
6375444 查看本文章
第二个:custom2.js
"use strict";
//引入上面抛出的模块,注意这里引入的是上面的文件名
let test = require("./custom1");
//使用custom1抛出的hello函数
test();
总结:
1.在Node中使用require引入模块(不管是自定义的还是内置的)
2.使用test存储custom1.js文件使用module.exports抛出的内容
3.module.exports抛出的内容可以是任何东西(字符串、函数、对象等)
4.引入自定义模块的时候需要在前面加上"./",否则可能会报错,不加"./"它会去内置模块查找该模块
5.在Node中引入的内置模块更多的是使用"."来使用这个模块中的内容的,其实我们也是可以这样使用,只需要在抛出内容的时候抛出的是对象即可
例如我们再custom1.js文件使用module.exports抛出东西的后可以这样:
module.exports = {"hello" : hello};
这样我们就可以在custom2.js的文件中使用 test.hello() 的形式来使用hello方法