Skip to main content

How to ignore lots of folders in Spotlight

I searched my Mac recently, and my results were cluttered with files from node_modules folders:

Screenshot of a search tool for the word 'inspect'. It shows a list of nine results, each with a path under it that goes to a subpath of a node_modules folder.

I can see why this happened – I’ve been working on several Node projects, and the node_modules folder is a cache of external Node dependencies. It contains all the third-party code used in those projects, and that’s a lot of files. It’s unsurprising that some of them would look like the files I’m actually looking for.

It’s also very annoying. I’m usually looking for the code that I’ve written, whereas the first two pages of search results were all third-party code I just happen to be using. I pretty much never want to see these files in a global file search.

I wanted to find a way to ignore these files in search.

On the Mac, file search is powered by Spotlight. You can either search in Spotlight directly, or other apps can use the Spotlight search index. (That’s what you see in the screenshot – I’m using an app called Alfred rather than Spotlight, but Alfred is using the Spotlight index to get a list of files.)

I can exclude a file or folder from Spotlight by adding it to a list in System Preferences, but it’s a manual process that needs me to click around. I have dozens of node_modules folders I want to ignore – is there a faster way to get them out of search results?

(Each project is really a collection of small apps that work together, and each app has its own node_modules folder. Finding the folder for each app gets tedious fast.)

I found a blog post that explains how to programmatically add Spotlight exclusions. The Spotlight configuration is kept in a plist file, and the post has several shell commands using plutil which add the config to exclude a folder.

I’ve wrapped these commands in a Python script that looks for every folder called node_modules, and excludes it from Spotlight. It also looks for folders called target, which is the output folder used by the Rust and Scala compilers, but you could modify it to look for any folder name.

Here’s how it works:

You need to run as the root user or using sudo, because regular users aren’t allowed to modify the Spotlight configuration file.

If you’d find this useful, you can download and use my script:

ignore_folders_in_spotlight.py