Apple - Prevent spotlight from indexing folders with a certain name

There is no known method to exclude from Spotlight a file or a folder based on a pattern (ex.: its name).

However it's possible to exclude a folder from Spotlight by adding to it an empty file .metadata_never_index.

You can use this method to ignore all node_moduleand bower_modules folders:

find /path/to/projects -type d  -path '*node_modules/*' -prune -o -type d -name 'node_modules' -exec touch '{}/.metadata_never_index' \;

Edit:

It look like the method .metadata_never_index is ignored by Spotlight since Mojave.


Edit 2:

As @JohnLee pointed it out, the extended attribute com.apple.metadata:com_apple_backup_excludeItem is not related / doesn't have any impact on Spotlight.

However *.noindex and symlink aren't indexed by mds (the backend of Spotlight). You can use it as band-aid:

# Rename all node_modules to node_modules.noindex and create a symlink node_modules -> node_modules.noindex
find /path/to/projects -type d \( -path '*node_modules/*' -o -path '*node_module.noindex/*' \) -prune -o -type d -name 'node_modules' -exec mv '{}' '{}.noindex' \; -exec ls -s '{}.noindex' '{}' \;

Note: if you use npm-ci, the node_modules is "automatically removed before npm ci begins its install".


In case anyone missed fsb's comment in the question, as I did. Apple provides a privacy tab in the Spotlight settings.

Goto "System Preferences" > "Spotlight" > "Privacy" > "+" Add folders to the list.

Note: This may not work immediately, I had to restart Spotlight to see the effects.


Apparently adding '.noindex' to a parent folder name will prevent Spotlight from indexing.

NB: I haven't personally verified.