ハトネコエ Web がくしゅうちょう

プログラミングやサーバー・Web制作、チームマネジメントなど得た技術のまとめ

指定ディレクトリ以下の node_modules ディレクトリをすべて消す

node_modules ディレクトリは物によっては数百MBもの大きさになるので、
放ったままにしておくのはディスク領域の無駄となる。

そこで node_modules ディレクトリをすべて削除してしまいたいと考えていたところ、
とてもいい記事を見つけた。

How to Delete ALL node_modules folders on your machine and Free up HD space!

ここで、 node_modules にどれだけの容量を使っているのかを知るコマンド
それらを全て削除するコマンドが説明されていた。ありがたい。

node_modules にどれだけの容量を使っているか

find . -name "node_modules" -type d -prune | xargs du -chs

find コマンドで node_modules ディレクトリを探し、
prune オプションによってそれより下層のディレクトリは結果として出力しない。
で、 xargsdu コマンドに渡してあげて、ディレクトリごとの容量を見ているわけだ。

プログラミングデータをまとめているディレクトリで実行してみたところ、
以下のようになった。

 60M   ./isucon/isucon8/backup/isucon/torb/webapp/nodejs/node_modules
 34M    ./isucon/isucon8/backup/isucon/local/node/lib/node_modules
## (中略)
250M    ./practice/react/my-app/node_modules
101M    ./practice/rails/rails6-practice/node_modules
8.0G   total

なんと驚きの 8.0GB も node_modules に使用していた。

必要になったら再び npm install すればいいので、これらは削除してしまいたい。

すべての node_modules ディレクトリを削除

find . -name "node_modules" -type d -prune -exec rm -rf '{}' +

先ほどの探索コマンドに、exec オプションを付けて実行をしている形である。
つまりは以下のコマンドと同義である。

find . -name "node_modules" -type d -prune | xargs rm -rf

xargs の -p オプションを付けて実行すると、何が削除されるのか表示されるのでより安全。
(表示までやや時間がかかります)

find . -name "node_modules" -type d -prune | xargs -p rm -rf

node_modules ディレクトリごと削除されるので、
node_modules ディレクトリは残してその下層のファイルのみ削除したい場合は別のコマンドを考える必要がある。
自分はいくらか試したが、どうにも上手くいかなかったので、特に困らないし node_modules ディレクトリごと削除する方向に落ち着いた。