4、系统模块
(1)什么是系统模块
Node运行环境提供的API. 因为这些API都是以模块化的方式进行开发的, 所以我们又称Node运行环境提供的API为系统模块
例:文件模块
(2)系统模板fs文件操作
f:file 文件 ,s:system 系统,文件操作系统。
const fs = require('fs');
1
读取文件内容
fs.reaFile('文件路径/文件名称'[,'文件编码'], callback);
1
注:callback 为回调函数
示例:
// 1.通过模块的名字fs对模块进行引用
const fs = require('fs');
// 2.通过模块内部的readFile读取文件内容
fs.readFile('./01.helloworld.js', 'utf8', (err, doc) => {
// 如果文件读取出错err 是一个对象 包含错误信息
// 如果文件读取正确 err是 null
// doc 是文件读取的结果
console.log(err);
console.log(doc);
});
写入文件内容
fs.writeFile('文件路径/文件名称', '数据', callback);
1
const content = '<h3>正在使用fs.writeFile写入文件内容</h3>';
fs.writeFile('../index.html', content, err => {
if (err != null) {
console.log(err);
return;
}
console.log('文件写入成功');
});
(3)系统模块path 路径操作
为什么要进行路径拼接
不同操作系统的路径分隔符不统一
/public/uploads/avata
Windows 上是 \ /
Linux 上是 /
路径拼接语法
path.join('路径', '路径', ...)
// 导入path模块
const path = require('path');
// 路径拼接
let finialPath = path.join('itcast', 'a', 'b', 'c.css');
// 输出结果 itcast\a\b\c.css
console.log(finialPath);
// public/uploads/avata
const path = require('path');
const finalPath = path.join('public', 'uploads','avatar');
console.log(finalPath);
相对路径VS绝对路径
大多数情况下使用绝对路径,因为相对路径有时候相对的是命令行工具的当前工作目录
在读取文件或者设置文件路径时都会选择绝对路径
使用__dirname获取当前文件所在的绝对路径
const fs = require('fs');
const path = require('path');
console.log(__dirname);
console.log(path.join(__dirname, '01.helloworld.js'))
fs.readFile(path.join(__dirname, '01.helloworld.js'), 'utf8', (err, doc) => {
console.log(err)
console.log(doc)
});
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。