Node运行环境提供的API. 因为这些API都是以模块化的方式进行开发的, 所以我们又称Node运行环境提供的API为系统模块
1.系统模块fs 文件操作
f:file 文件 ,s:system 系统,文件操作系统。
//引入文件模块
const fs = require('fs');
1.1 读取文件内容
- fs.reaFile('文件路径/文件名称'[,'文件编码'], callback);
代码示例
//引入fs模块
const fs = require('fs');
//通过模块内部的readFile读取文件内容
fs.readFile('./1.helloword.js', 'utf8', (err, doc) => {
// 如果文件读取出错err 是一个对象 包含错误信息
// 如果文件读取正确 err是 null
// doc 是文件读取的结果
console.log('>>>>>'+err);
console.log(doc);
});
1.2 写入文件内容
- fs.writeFile('文件路径/文件名称', '数据', callback);
代码示例
const fs = require('fs');
fs.writeFile('./helloword.txt', '我是写入的数据', err => {
if (err != null) {
console.log(err)
return;
}
console.log('文件写入成功');
});
1.3 读取文件夹
- fs.readdir('文件路径/文件名称', 对象, callback);
- dirent是通过fs获取到的一个文件对象
- dirent.isDirectory() 判断是否是一个文件夹
- dirent.isFile() 判断是否是一个文件
- dirent.name 返回文件或者文件夹的名称
代码示例
//引入fs模块
const fs = require('fs');
//读取文件夹
fs.readdir('./gulp-demo',{withFileTypes:true}, function (err, dir) {
if (err != null) {
console.log(err);
return;
}
// fs.Dirent 类
// 1)dirent.isDirectory() 判断是否是一个文件夹
// 2)dirent.isFile() 判断是否是一个文件
// 3)dirent.name 返回文件或者文件夹的名称
for (var i in dir) {
console.log(dir[i].name+'------'+dir[i].isDirectory()+'-------'+dir[i].isFile());
}
});
dist------true-------false
glup相关方法.txt------false-------true
gulpfile.js------false-------true
node_modules------true-------false
src------true-------false
1.4 文件监听
fs.watch(filename[, options][, listener])
- 成功调用 fs.watch 方法将返回一个新的 fs.FSWatcher 对象。所有 fs.FSWatcher 对象每当修改指定监视的文件,就会触发 'change' 事件
// 引入fs模块
const fs = require('fs');
//eventType 可以是 'rename' 或 'change'
//当改名或出现或消失的时候触发rename
//recursive:是否监听到内层子目录,默认false;
let myWatch = fs.watch('./watch', {encoding: 'utf8', recursive: true}, (event, filename) => {
if (event == 'change') {
console.log(event + 'change事件触发了')
}
if (event == 'rename') {
console.log(event + 'rename事件触发了')
}
//encoding:文件名编码格式,buffer、默认:utf8等;
//filename有可能为空
if (filename) {
console.log('filename:::', filename)
}
});
//change 事件会触发多次 监听事件注册
myWatch.on('change', function (err, filename) {
console.log(filename + '发生变化');
});
//5秒后关闭监视
setTimeout(function () {
myWatch.close();
},5000);
fs 相关api文档地址请点击
2. 系统模块path 路径操作
2.1 路径拼接语法
- path.join('路径', '路径', ...)
代码示例
//引入path模块
const path = require('path');
//路径拼接
var finalPath = path.join('public', 'upload', 'avatar','a.jpg');
//输出结果public\upload\avatar\a.jpg
console.log(finalPath);
2.2 相对路径VS绝对路径
- 大多数情况下使用绝对路径,因为相对路径有时候相对的是命令行工具的当前工作目录
- 在读取文件或者设置文件路径时都会选择绝对路径
- 使用__dirname获取当前文件所在的绝对路径
代码示例
//引入fs模块
const fs = require('fs');
//引入path模块
const path=require('path');
console.log(__dirname);
console.log(path.join(__dirname,'1.helloword.js'));
fs.readFile(path.join(__dirname,'1.helloword.js'), 'utf8', (err, doc) => {
console.log(err);
console.log(doc)
});