1:JavaScript开发弊端
JavaScript在使用时存在两大问题,文件依赖和命名冲突
2: Node.js中模块化开发规范
-
Node.js规定一个JavaScript文件就是一个模块,模块内部定义的变量和函数默认情兄下在外部无法得到
-
模块内部可以使用exports对象进行成员导出,使用require方法导入其他模块。
例:dom1.js 导出文件
let ve=1; //定义了一个变量
const sy = name => `你好, ${
name}`;//定义一个方法
//向模块化外部导出数据
exports.ve=ve;
exports.sy=sy;
gom.js 导入文件
//模块成员进行导入
//在gom.js模块中导入dom1模块
let gom=require('./dom1');
//输出dom1模块ve变量
console.log(gom.v);
//输出方法
console.log(gom.s('小明'));
运行gom.js
模块成员导出的另一种方式(module)
例:a.js
const g =name => `hello ${
name}`;
module.exports.gz=g;
b.js
const b=require('../模块化/a');
console.log(b.gz('小明'));
运行b.js
模块导出两种方式的联系与区别
exports是module.exports的别名(地址引用关系),导出对象最终以module.exports为准.
- 当export和module.exports指向同个对象时,二者是等价的
例:a.js
const g =name => `hello ${
name}`;
const x=100;
exports.x=x;
module.exports.gz=g;
b.js
const b=require('../模块化/a');
// console.log(b.gz('小明'));
console.log(b);
你可以发现 x:100照样可以输出
- 当export和module.exports指向不同个对象时,以module.exports为准
例:a.js
module.exports={
name:'张三'
}
exports={
age:20
}
b.js
const b=require('../模块化/a');
console.log(b);
你可以发现最终输出的是module.exports的值
3:系统模块
什么是系统模块
Node运行环境提供的APl.因为这些API都是以模块化的方式进行开发的,所以我们又称Node运行环境提供的API为系统模块
系统模块fs文件操作
f:file文件,s:system系统,文件操作系统。
(1)读取文件内容
fs.reaFile('文件路径/文件名称'[,'文件编码’],ca1lback);
ca1lback是一个回调函数
例 readfile.js
//系统模块
const fs=require('fs');
//通过readFile读取文件内容
fs.readFile('./a.js','utf8',(err,doc) =>{
console.log(err);
console.log(doc);
})
读取过程是硬盘读取 err是错误信息,doc是文件读取的内容
运行你可以发现它将a.js的内容读取下来了
(1)写入文件内容
fs.writeFile('文件路径/文件名称‘,’数据’,callback);;
ca1lback是一个回调函数
例:wirefile.js
const fs=require('fs');
fs.writeFile('./doex.txt','插入的数据',err =>{
if(err!=null){
console.log('有错误');
}
console.log('插入成功');
})
运行你可以发现插入成功了,doex.txt里面也有插入的数据
系统模块path 路径操作
为什么要进行路径拼接?
- 不同操作系统的路径分隔符不统一
- /public/uploads/avatar
- Windows上是\ /
- Linux上是/
路径拼接语法:path.join(路径’,路径,…)
//比如拼接//public/uploads/avater目录
const path=require('path');
const pj=path.join('public','uploads','avater');
console.log(pj);
相对路径VS绝对路径
-
大多数情况下使用绝对路径,因为相对路径有时候相对的是命令行工具的当前工作目录
-
在读取文件或者设置文件路径时都会选择绝对路径
-
使用dirname获取当前文件所在的绝对路径