系统模块fs,文件操作
时间:2020-07-01 01:03:40
收藏:0
阅读:96
1. 读文件内容
// 1. 通过模块的名字fs对模块进行引用 const fs = require(‘fs‘); // 2. 通过模块内部的readFile读取文件内容 fs.readFile(‘../css/base.css‘, ‘utf-8‘, (err, doc) => { // 如果文件读取发生错误,参数err的值为错误对象,否则err的值为null // doc参数为文件内容 if(err === null) { // 在控制台输出文件内容 console.log(doc); } });
2. 写文件内容
// 1. 通过模块的名字fs对模块进行引用 const fs = require(‘fs‘); 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/avatar
- windows上是\ /
- linux上是 /
const path = require(‘path‘); const finalpath = path.join(‘public‘, ‘uploads‘, ‘avatar‘); console.log(finalpath);
4.相对路径vs绝对路径
- 大多数情况下,使用绝对路径,因为相对路径有时候相对的是命令行的当前工作目录
- 在读取文件或者设置文件路径时都会选择绝对路径
- 使用__dirname获取当前文件所在的绝对路径
5.第三方模块nodemon
原文:https://www.cnblogs.com/guwufeiyang/p/13216699.html
评论(0)