macos_node_modules_fix

This script will exclude all node_modules directories in the given directory ($PWD if not given) and its subdirectories from Time Machine backups and prevent their Spotlight indexing.

Copy the script into your Node.js project and add it as a preinstall life cycle script to your package.json file:

package.json
{
...
  "scripts": {
    "preinstall": "scripts/macos–node-modules-fix.sh"
  }
}

For this to work, NPM should not ignore pre- or post-scripts (the default).

For security reasons you might want to disable them globally via:

$ npm config set ignore-scripts true

Use --no-ignore-scripts to enable the pre- or post-scripts for a specific NPM command:

$ npm install --no-ignore-scripts

You can show your current configuration via:

$ npm config ls -l

Alternatively, you can use this script as custom script in your package.json file:

package.json
{
...
  "scripts": {
    "macos:fix-node-modules": "scripts/macos–node-modules-fix.sh"
  }
}

And execute it manually:

$ npm install && npm run macos:fix-node-modules

Usage

$ scripts/nodejs/macos–node-modules-fix.sh
$ scripts/nodejs/macos–node-modules-fix.sh /tmp/example_project

$ xattr -r /tmp/example_workspace
$ tree --noreport -a /tmp/example_workspace
/tmp/example_workspace
├── project1
│   └── node_modules
└── project2
    └── node_modules
$ scripts/nodejs/macos–node-modules-fix.sh /tmp/example_workspace
$ xattr -r /tmp/example_workspace                                         (1)
/tmp/example_workspace/project1/node_modules: com.apple.metadata:com_apple_backup_excludeItem
/tmp/example_workspace/project2/node_modules: com.apple.metadata:com_apple_backup_excludeItem
$ tree --noreport -a /tmp/example_workspace
/tmp/example_workspace
├── project1
│   └── node_modules
│       └── .metadata_never_index                                         (2)
└── project2
    └── node_modules
        └── .metadata_never_index                                         (2)
1 node_modules directories are not backed up by Time Machine
2 Spotlight indexing prevented