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,并发送请求。

相关推荐
用户2160763408310 小时前
一个 2 MB 的 .zst 文件,解压出来只有十几 KB
node.js
木头左2 天前
【浏览器自动化】用 CDP 接管本机 Chrome:从一个宿主迁到另一个宿主的设计与踩坑
node.js·浏览器自动化·cdp·技能化·踩坑实践
cpolar技术支持2 天前
把 agent-autoloop 装在 Mac 上:用本机 Node 实跑一次「接活—提问—拍板—接着干」,再用 cpolar 把它的状态页开给不在工位的自己
node.js·内网穿透·cpolar·ai agent·agent-autoloop
SEO_juper3 天前
Node.js 全站 SEO 体检报告生成器:一次查完标题、描述、canonical、H1、图片
开发语言·前端·node.js·html·bash
木头左4 天前
【Node.js】Markdown 转带图片 Word 文档实战:docx 库转换器设计与 5 个踩坑
node.js·word·markdown·文档自动化
思特奇时空智能4 天前
大规模点要素地图渲染性能优化实践
vue.js·arcgis·性能优化·node.js·html·gis·webgl
w3296362716 天前
飞书接单到月度结算:我用一个 DSH 插件跑通鞋类采购 WMS,附 22 项验收
pdf·node.js·飞书·后端开发·ai agent
濮水大叔6 天前
Cabloy/Vona 为什么不需要 NestJS 的 Dynamic Module
typescript·node.js·nestjs
匠云创新6 天前
读完一万段要两分钟:我们把标书读取从 WPS 对象模型搬到了 docx 解析
性能优化·node.js
某哈压力大7 天前
SSH 突然 Connection reset?不是密钥坏了,是 OpenSSL 把 sshd 干趴了
前端·node.js·命令行