You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Node.js删除目录下所有文件和子目录且保留原目录

方案1:使用Node.js原生fs模块(无需第三方依赖)

要求Node.js版本 ≥ 14.14.0,可直接使用内置fs模块实现,示例代码如下:

异步实现(推荐)

const fs = require('fs/promises');
const path = require('path');

// 传入要清空的目录路径,默认是当前目录下的Test文件夹
const clearDirectory = async (dirPath = './Test') => {
  // 读取目录下的所有文件/子文件夹条目
  const dirEntries = await fs.readdir(dirPath, { withFileTypes: true });
  // 遍历删除所有条目
  for (const entry of dirEntries) {
    const entryFullPath = path.join(dirPath, entry.name);
    // recursive: true 支持删除嵌套文件夹,force: true 忽略文件不存在的报错
    await fs.rm(entryFullPath, { recursive: true, force: true });
  }
};

// 调用方法
clearDirectory()
  .then(() => console.log('Test目录清空完成'))
  .catch(err => console.error('清空失败:', err));

同步实现

const fs = require('fs');
const path = require('path');

const clearDirectorySync = (dirPath = './Test') => {
  const dirEntries = fs.readdirSync(dirPath, { withFileTypes: true });
  for (const entry of dirEntries) {
    const entryFullPath = path.join(dirPath, entry.name);
    fs.rmSync(entryFullPath, { recursive: true, force: true });
  }
};

// 调用方法
try {
  clearDirectorySync();
  console.log('Test目录清空完成');
} catch (err) {
  console.error('清空失败:', err);
}
方案2:使用fs-extra库(代码更简洁)

fs-extra是Node.js原生fs的增强库,内置了直接清空目录的API,无需自己实现遍历逻辑:

  1. 首先安装依赖:
npm install fs-extra
  1. 调用方法:

异步实现

const fsExtra = require('fs-extra');

// emptyDir会自动清空目录内所有内容,保留目录本身,若目录不存在还会自动创建
await fsExtra.emptyDir('./Test');

同步实现

const fsExtra = require('fs-extra');

fsExtra.emptyDirSync('./Test');
注意事项
  • 建议使用path.resolve()处理目标目录的绝对路径,避免相对路径引发的误删风险
  • 生产环境使用前建议添加路径校验,确认目标路径是预期要清空的目录
  • 删除类操作建议先在测试环境验证逻辑正确性后再上线

内容的提问来源于stack exchange,提问作者Harald

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 05:15:03