Prevent spotlight from indexing folders with a certain name

indexingspotlight

Is there a way to globally ignore folders with a certain name (say node_modules)

I know I can do it manually for each instance but I was wondering if its possible to just let spotlight know not to index these folders? node_modules, for example, typically has thousands of files that I don't want to search and it ends up slowing down spotlight.

I've looked around but I can only find answers that suggest manually adding folders in spotlight privacy list. Does someone have a better, glob way to it?

Best Answer

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".