写了一个清理node_modules的工具

最近笔记本的磁盘空间快满了,就想着清一下,在查找大文件的时候,发现node_modules竟然占了十几个G,果然是个黑洞。

一个一个删显然效率太低,又不想把整个项目都删掉,那只能写个程序一键清除node_modules文件夹了。

解铃还须系铃人,既然是node导致的问题,那我们也用node解决(当然其他语言也可以)。

废话不多说,下面是代码

import { existsSync } from 'fs';
import { opendir, rm } from 'fs/promises';
import path from 'path';

const dir = 'C:/Users/16019/Desktop/demo'; // 搜索目录
const searchDepth = 5; // 搜索深度,如果是负数,则一直搜索到没有目录为止

async function searchAndRemove(dir, searchDepth) {
  if(searchDepth === 0 || !existsSync(dir)) return;

  try {
    const dirents = await opendir(dir);
    for await (const dirent of dirents) {
      if(dirent.isFile()) continue;

      const subDir = path.resolve(dir, dirent.name);
      if(dirent.name === 'node_modules') {
        console.log(`正在删除${subDir}`);
        rm(subDir, { recursive: true, force: true });
      }else {
        searchAndRemove(subDir, searchDepth - 1);
      }
    }
  } catch (error) {
    console.error(error);
  }
}

searchAndRemove(dir, searchDepth);

使用方式:

  1. 准备好Node.js,需要14.14.0+
  2. 新建一个main.mjs文件(注意后缀是.mjs,因为使用了es module的写法)
  3. 在当前目录执行node main.mjs
posted @ 2021-12-01 16:15  JoeyHua  阅读(296)  评论(0编辑  收藏  举报