跳到主要内容

文件系统

文件系统模块提供了一套全面的 API 用于文件和目录操作。它采用单例模式,通过 fs 实例访问。

概述

文件系统模块提供统一的接口用于:

  • 文件和目录管理
  • 文件内容操作
  • 压缩和解压缩
  • 文件系统事件监控

特性

  • 文件和目录管理(创建、删除、重命名、移动、复制)
  • 文件内容操作(读取、写入、追加)
  • 压缩和解压缩(zip、tar)
  • 文件系统事件监控
  • 跨平台路径处理
  • 支持 Promise 的异步操作

示例

列出文件和目录

// 列出目录中的所有项目
const items = await fs.ls('/path/to/directory');

// 仅列出目录
const directories = await fs.ls('/path/to/directory', true);

文件和目录管理

// 检查路径是否存在
const exists = await fs.exists('/path/to/file');

// 检查路径是否为目录
const isDir = await fs.isDirectory('/path/to/directory');

// 检查路径是否为文件
const isFile = await fs.isFile('/path/to/file');

// 创建目录
await fs.mkdir('/path/to/new/directory', true); // true 表示创建父目录

// 删除文件
await fs.rm('/path/to/file');

// 删除目录
await fs.rmdir('/path/to/directory', true); // true 表示递归删除

// 重命名文件或目录
await fs.ren('/path/to/old', 'new-name');

文件内容操作

// 读取文件内容
const content = await fs.read('/path/to/file');

// 写入内容到文件
await fs.write('/path/to/file', 'content', 'truncate'); // truncate、create 或 append

// 创建空文件
await fs.touch('/path/to/file');

文件复制和移动

// 复制文件或目录
await fs.cp('/path/to/source', '/path/to/target');

// 移动文件或目录
await fs.mv('/path/to/source', '/path/to/target');

压缩和解压缩

// 压缩文件为 ZIP
await fs.zip(['/path/to/file1', '/path/to/file2'], '/path/to/archive.zip');

// 解压 ZIP 文件
await fs.unzip('/path/to/archive.zip', '/path/to/extract/to');

// 创建 TAR 归档
await fs.tar(['/path/to/file1', '/path/to/file2'], '/path/to/archive.tar', 'gzip');

// 解压 TAR 归档
await fs.untar('/path/to/archive.tar', '/path/to/extract/to', 'gzip');

最佳实践

  1. 路径处理

    • 尽可能使用绝对路径
    • 正确处理路径分隔符以确保跨平台兼容性
    • 操作前验证路径
  2. 资源管理

    • 清理临时文件
    • 为文件操作使用适当的写入模式
    • 谨慎处理大文件
  3. 错误处理

    • 为所有文件操作实现适当的错误处理
    • 操作前检查文件是否存在
    • 适当处理权限错误
    • 使用 try-catch 块进行错误处理:
    try {
    await fs.write('/path/to/file', 'content');
    } catch (error) {
    console.error('写入文件时出错:', error);
    }
  4. 性能优化

    • 对大文件传输使用流式处理
    • 实现适当的缓存机制
    • 尽可能批量处理操作
    • 为归档文件选择适当的压缩模式