node内置模块

1.path模块

path模块可用于路径拼接

1
2
3
4
const path = require('path');
const basePath = 'ser/why'
const fileName = 'abc.txt'
const filePath = path.resolve(basePath,fileNmae)

用的最多的就是path.resolve

关于路径拼接, 还有另一种方式

1
const fileName  = path.join(basePath,fileName)

join,可以拼接三个或者多个路径,但是join并不会智能解析前面的’../‘

而resolve可以智能解析前面的../将其解释为真实路径

获取路径信息

path.dirname(path)//表示文件路径

path.extname(path)//表示文件扩展名

path.basename(path)//表示文件名称

2.fs模块,文件读写

1
2
const info = fs.statSync(filePath);
//同步操作
1
2
3
4
5
6
7
8
9
10
//异步操作
fs.stat(filePath,(err,info)=>{
if(err){
log(err)
}
return;
})
log(info)
log(info.isFile());//是否是文件
log(info.isDirectory);//是否是文件夹
1
2
3
4
5
6
//promise方式
fs.promise.stat(filePath).then(info=>{
log(info)
}).catch(err=>{
log(err)
});

文件读写:

文件写入

1
2
3
4
5
6
7
const fs = require('fs');
const content="新文本"
fs.writeFile('./aaa.txt',content,{flag:'a'},err=>{
console.log(err);
})
//其中flag表示类型,a就是写入类型
//另外还有一个可选为encoding,编码类型
1
2
3
4
//文件读取
fs.readFile('./aaa.txt', { encoding: 'utf-8' }, (err, data) => {
console.log(data);
})