关于前端:Nodejs-基础学习记录三

5次阅读

共计 712 个字符,预计需要花费 2 分钟才能阅读完成。

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 获取以后文件所在的绝对路径
正文完
 0