2. 零碎模块

2.1 什么是零碎模块

Node运行环境提供的API. 因为这些API都是以模块化的形式进行开发的, 所以咱们又称Node运行环境提供的API为零碎模块

2.2 零碎模块fs 文件操作

f:file 文件 ,s:system 零碎,文件操作系统。

const fs = require('fs');

读取文件内容

fs.reaFile('文件门路/文件名称'[,'文件编码'], callback);
2.2 零碎模块fs 文件操作

写入文件内容

 const content = '<h3>正在应用fs.writeFile写入文件内容</h3>'; fs.writeFile('../index.html', content, err => {   if (err != null) {        console.log(err);       return;   }   console.log('文件写入胜利'); });
2.3 零碎模块path 门路操作

为什么要进行门路拼接

  • 不同操作系统的门路分隔符不对立
  • /public/uploads/avatar
  • Windows 上是 \ /
  • Linux 上是 /
2.4 门路拼接语法
path.join('门路', '门路', ...)
  // 导入path模块 const path = require('path');  // 门路拼接 let finialPath = path.join('itcast', 'a', 'b', 'c.css');  // 输入后果 itcast\a\b\c.css console.log(finialPath);
2.5 相对路径VS绝对路径
  • 大多数状况下应用绝对路径,因为相对路径有时候绝对的是命令行工具的当前工作目录
  • 在读取文件或者设置文件门路时都会抉择绝对路径
  • 应用__dirname获取以后文件所在的绝对路径