模块概念、自定义模块、常用模块、三方模块
为了让Node.js的文件可以相互调用,Node.js提供了一个简单的模块系统。
模块是Node.js 应用程序的基本组成部分,文件和模块是一一对应的。换言之,一个 Node.js 文件就是一个模块,这个文件可能是JavaScript 代码、JSON 或者编译过的C/C++ 扩展。
1、创建自定义模块
使用exports
方式
exports.reqest = function(){
console.log('request请求')
}
exports.get = function(){
console.log('get请求')
}
exports.post = function(){
console.log('post请求')
}
使用module.exports
方式
var app = {
name: '天气',
version: '1.0.0',
build: function(){
console.log('构建app')
}
}
module.exports = app
模块导入使用
const module1 = require('./custom_module.js')
const module2 = require('./custom_module2.js')
//使用
console.log(module2.name)
module1.get()
2、npm安装三方模块
上面说明了使用自定义模块,nodejs为我们提供了很多官方和三方开发人员书写的模块,可以帮我们简化开发工作,nodejs模块可以在npm上查找使用https://www.npmjs.com/
安装三方模块,这里简单介绍安装axios
,这是一个很常用的网络请求模块,有很强大的功能。
npm install axios --save
通过上面的方式,就会将模块axios
加入到项目中,并且将依赖关心写入到package.json
文件中。你在其他地方拉下来项目,直接使用npm i
或者 npm install
就能安装正常使用了。
有时候,可能需要安装指定版本。可以使用@+版本号方式安装
npm install axios@1.0.0 --save
3、fs模块
引入fs
模块
const fs = require('fs')
fs.stat
检测是文件夹还是文件
//检测是文件还是目录
fs.stat('./impor_module.js', function(error, data){
if(error){
console.log("报错了: " + error);
return;
}
if(data.isFile){
console.log("是文件");
}else{
console.log("是文件夹");
}
})
fs.mkdir
创建目录
//判断目录是否存在
fs.exists('./scc', function(exists){
if(!exists){
//如果不存在,创建目录
fs.mkdir('./scc', function(error){
if(error){
console.log(error)
return
}
console.log('目录创建成功!')
})
}else{
//目录已存在,执行后续操作
console.log('目录已存在')
}
})
创建文件夹,如果要一次性创建多层的话,可以用到一个三方模块,大大减少我们的操作。
npm install -g mkdirp
使用
var mkdirp = require('mkdirp');
mkdirp('/tmp/foo/bar/baz', function (err) {
if (err) console.error(err)
else console.log('pow!')
});
对于fs
模块,就简单介绍两个,后续其他的使用到的时候,可以自行查找文档。
参考:
1、Node.js模块系统: https://www.runoob.com/nodejs/nodejs-module-system.html
2、终于讲清楚了nodejs中exports和module.exports的区别: https://blog.csdn.net/qq_31967569/article/details/82461499
3、npm常用模块之mkdirp使用: https://www.cnblogs.com/jiaoshou/p/12187136.html