Node.js核心模块:fs、path与http详解

1.fs模块

fs 是 Node.js 的核心模块之一,用于与文件系统进行交互。它提供了大量用于读取、写入、更新、删除文件和目录的 API。

1.1 核心特点

  1. 无需安装,直接 require('fs') 即可使用。
  2. 支持异步与同步两种形式 :大多数方法都有同步版本(如 readFileSync)和异步版本(如 readFile)。
  3. 回调风格 :异步方法默认使用回调函数(Node.js 风格:(err, data) => {}
  4. Promise 支持 :从 Node.js v10 起,可以使用 fs.promises 获取基于 Promise 的 API。

1.2 常用API

1.2.1 读取文件

javascript 复制代码
const fs = require('fs');

// 异步读取
fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

// 同步读取
const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);

1.2.2 写入文件

javascript 复制代码
// 异步写入(会覆盖原有内容)
fs.writeFile('output.txt', 'Hello Node.js', (err) => {
  if (err) throw err;
  console.log('文件已保存');
});

1.2.3 追加内容和删除文件

javascript 复制代码
// 向log.txt文件中添加新的日志+\n(换行)
fs.appendFile('log.txt', '新的日志\n', (err) => {
  if (err) throw err;
});


// 删除文件
fs.unlink('oldfile.txt', (err) => {
  if (err) throw err;
  console.log('文件已删除');
});

1.2.4 使用Promise风格

javascript 复制代码
const fs = require('fs').promises;

async function example() {
  try {
    const data = await fs.readFile('example.txt', 'utf8');
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

example();

2.path模块

path 也是 Node.js 的核心模块之一,专门用来处理和转换文件路径字符串。它不关心磁盘上是否真的存在这个路径,只负责"字符串层面的路径运算"。

2.1 常用API

2.1.1 绝对路径

path.resolve([...paths]),把相对路径解析成绝对路径,以当前工作目录为基准。

javascript 复制代码
const path = require('path');

// 把"当前文件所在目录"与"文件路径"片段拼接并解析成绝对路径
console.log(path.resolve(__dirname, '文件路径'));

// 假设当前文件是 /home/alex/proj/src/tool.js,就可以写成下述的情况
console.log(path.resolve(__dirname, 'log.txt'));

2.1.2 路径拼接

javascript 复制代码
const path = require('path');

//安全拼接
const full = path.join('src', 'components', 'Button.tsx');
//src/components/Button.tsx   (Windows 下自动用反斜杠)

3.http模块

http 是 Node.js 最核心 的网络模块之一,零依赖就能创建 HTTP 服务器或发起 HTTP 请求(客户端)。

3.1 使用方法

  1. 服务端http.createServer() → 监听端口 → 响应请求

  2. 客户端http.get() / http.request() → 向外发请求(类似浏览器 fetch),在listen中添加请求。

javascript 复制代码
// server.js
const http = require('http');

const server = http.createServer((req, res) => {
  console.log(`${req.method} ${req.url}`);       // 打日志
  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
  // end表示结束响应,可选最后一段数据
  res.end('你好,世界\n');
});

server.listen(3000, () => {
  console.log('Server ready → http://localhost:3000');
  // 服务器就绪后,自己作为客户端向自己发请求
  http.get('http://localhost:3000/test', (res) => {
    let body = '';
    res.on('data', chunk => body += chunk);
    res.on('end', () => {
      console.log('[client] status:', res.statusCode);
      console.log('[client] headers:', res.headers);
      console.log('[client] body:', body);
      // 收到响应后退出end回调
      server.close();
    });
  })
});

然后在终端中运行node server.js,即可使用浏览器访问http://localhost:3000,并发送请求。

相关推荐
码路飞18 小时前
Node.js 中间层我维护了两年,这周终于摊牌了——成本账单算完我人傻了
node.js
None3212 天前
【NestJs】使用Winston+ELK分布式链路追踪日志采集
javascript·node.js
Dilettante2582 天前
这一招让 Node 后端服务启动速度提升 75%!
typescript·node.js
Mr_li2 天前
NestJS 集成 TypeORM 的最优解
node.js·nestjs
UIUV3 天前
node:child_process spawn 模块学习笔记
javascript·后端·node.js
前端付豪4 天前
Nest 项目小实践之注册登陆
前端·node.js·nestjs
天蓝色的鱼鱼4 天前
Node.js 中间层退潮:从“前端救星”到“成本噩梦”
前端·架构·node.js
codingWhat4 天前
uniapp 多地区、多平台、多环境打包方案
前端·架构·node.js
小p4 天前
nodejs学习: 服务器资源CPU、内存、硬盘
node.js
Mr_li4 天前
手摸手,教你如何优雅的书写 NestJS 服务配置
node.js·nestjs