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

相关推荐
teeeeeeemo6 小时前
Webpack 模块联邦(Module Federation)
开发语言·前端·javascript·笔记·webpack·node.js
全马必破三11 小时前
Node.js HTTP开发
网络协议·http·node.js
千叶寻-12 小时前
正则表达式
前端·javascript·后端·架构·正则表达式·node.js
无责任此方_修行中1 天前
谁动了我的数据?一个 Bug 背后的“一行代码”真凶
后端·node.js·debug
岁月宁静1 天前
AI 语音合成技术实践:实现文本转语音实时流式播放
前端·vue.js·node.js
Never_Satisfied1 天前
在JavaScript / HTML / Node.js中,post方式的Content-Type属性的text的三种编码
javascript·node.js·html
学习3人组1 天前
Node.js模块化开发实训案例
node.js·编辑器·vim
思考的笛卡尔1 天前
Node.js性能优化:从事件循环到内存管理
性能优化·node.js