Who Ate My Disk Space? It's "node_modules" Again! 🕵️‍♂️

maurerkrisztian

Krisztián Maurer

Posted on September 28, 2023

Who Ate My Disk Space? It's "node_modules" Again! 🕵️‍♂️

Hey there! If you've used Node.js, you've probably seen the node_modules folder. It's where all the extra stuff for your project goes. But sometimes, it gets really big, really fast. I wanted to know just how big, so I made a script to check it out.

Maurer Krisztian

What I Made:

It's a simple tool that looks through your projects, finds the node_modules folders, and tells you how big they are. And it uses colors to be cool!

Why I Made This:

  1. Curiosity: Which project has the biggest node_modules? 🤔
  2. Cleaning: Some folders just have too much stuff. 🧹
  3. Fun: I thought it'd be a fun little project. 😄
  4. AI: Can AI craft this for me? (Absolutely, with a bit of direction!)

The script

#!/bin/bash

# ANSI color codes
RED="\033[31m"
GREEN="\033[32m"
YELLOW="\033[33m"
RESET="\033[0m"

# Set the starting directory for the search. Default is root if no argument is provided.
START_DIR=${1:-/}

# Find top-level node_modules directories directly under a project within the specified directory
# and exclude those inside the .cache directory
directories=$(find "$START_DIR" -type d -name "node_modules" -not -path "*/node_modules/*/*" -not -path "*/.cache/*" 2>/dev/null)

total_size=0

# Loop through each directory and calculate its size
for dir in $directories; do
    # Check if the parent directory of node_modules is not another node_modules (to avoid nested ones)
    parent_dir=$(dirname "$dir")
    if [[ $(basename "$parent_dir") != "node_modules" ]]; then
        size=$(du -sh "$dir" | cut -f1)
        echo -e "${YELLOW}Size of $dir: ${GREEN}$size${RESET}"

        # Convert size to bytes for summation
        bytes=$(du -sb "$dir" | cut -f1)
        total_size=$((total_size + bytes))
    fi
done

# Convert total size back to human-readable format
human_readable_total=$(numfmt --to=iec-i --suffix=B $total_size)

echo -e "${RED}Total size of all top-level node_modules within $START_DIR: ${GREEN}$human_readable_total${RESET}"

Enter fullscreen mode Exit fullscreen mode

*gh gist

Want to Try? Here's How:

  1. Write down the script in node_modules_size.sh.
  2. Get it ready with: chmod +x node_modules_size.sh.
  3. Start it up: ./node_modules_size.sh.
  4. For a specific place: ./node_modules_size.sh /path/to/place.

Maurer Krisztian

Wrap Up

So, if you're wondering where all your computer's space went, this tool might help. Give it a go and see what you find! 🚀📁

💖 💪 🙅 🚩
maurerkrisztian
Krisztián Maurer

Posted on September 28, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related