fnm now supports Git-style hooks that allow you to execute custom scripts during various operations. This feature enables you to automate tasks such as environment setup, package installation, notifications, and cleanup.
The following hooks are currently supported:
pre-install: Executed before downloading and installing a Node.js versionpost-install: Executed after successful installation of a Node.js versioninstall-failed: Executed when Node.js installation fails
Hooks should be placed in the hooks/ subdirectory of your fnm directory:
- Default location:
~/.fnm/hooks/ - Custom location:
$FNM_DIR/hooks/(if you've set a custom FNM_DIR)
- Executable: Hook scripts must be executable (
chmod +x hook-name) - Any format: Scripts can be written in any language (shell, Python, Node.js, etc.)
- Return code: Hooks should return exit code 0 for success, non-zero for failure
- Error handling: If a hook fails, fnm will log the error but continue with the operation
The following environment variables are available to all hooks:
FNM_VERSION: The Node.js version being operated on (e.g., "v18.17.0")FNM_ARCH: The architecture being used (e.g., "x64", "arm64")FNM_DIR: The fnm installation directoryFNM_INSTALLATION_DIR: The specific installation directory for this version
#!/bin/bash
# ~/.fnm/hooks/pre-install
echo "π About to install Node.js $FNM_VERSION"
# Example: Send notification
osascript -e "display notification \"Installing Node.js $FNM_VERSION\" with title \"fnm\""
# Example: Clean up old caches
npm cache clean --force 2>/dev/null || true#!/bin/bash
# ~/.fnm/hooks/post-install
echo "β
Node.js $FNM_VERSION installed successfully"
# Example: Auto-install global packages
npm install -g pnpm yarn typescript
# Example: Set up development environment
if [ -f "./package.json" ]; then
echo "Installing project dependencies..."
npm install
fi
# Example: Send notification
osascript -e "display notification \"Node.js $FNM_VERSION ready!\" with title \"fnm\""#!/bin/bash
# ~/.fnm/hooks/install-failed
echo "β Failed to install Node.js $FNM_VERSION"
# Example: Log failure
echo "$(date): Failed to install $FNM_VERSION" >> ~/.fnm/install-failures.log
# Example: Send error notification
osascript -e "display notification \"Failed to install Node.js $FNM_VERSION\" with title \"fnm Error\""#!/usr/bin/env python3
# ~/.fnm/hooks/post-install
import os
import subprocess
import json
version = os.environ.get('FNM_VERSION')
install_dir = os.environ.get('FNM_INSTALLATION_DIR')
print(f"π Python post-install hook for Node.js {version}")
# Example: Update IDE settings
ide_config = {
"nodejs": {
"version": version,
"path": install_dir
}
}
with open(os.path.expanduser("~/.vscode/settings.json"), "w") as f:
json.dump(ide_config, f, indent=2)
print("Updated IDE configuration")#!/usr/bin/env node
// ~/.fnm/hooks/pre-install
const version = process.env.FNM_VERSION;
const arch = process.env.FNM_ARCH;
console.log(`π¦ Installing Node.js ${version} (${arch})`);
// Example: Check system requirements
const fs = require('fs');
const os = require('os');
if (os.freemem() < 1024 * 1024 * 1024) { // Less than 1GB free
console.warn('β οΈ Warning: Low memory detected');
}
// Example: Log installation attempt
const logEntry = {
timestamp: new Date().toISOString(),
version,
arch,
platform: os.platform()
};
fs.appendFileSync(
require('path').join(os.homedir(), '.fnm', 'install-log.json'),
JSON.stringify(logEntry) + '\n'
);#!/bin/bash
# Auto-install preferred package managers after Node.js installation
npm install -g pnpm@latest yarn@latest
corepack enable#!/bin/bash
# Set up development tools and configurations
# Install global development tools
npm install -g typescript eslint prettier nodemon
# Copy development configurations
cp ~/.dotfiles/tsconfig.json ./
cp ~/.dotfiles/.eslintrc.js ./#!/bin/bash
# Auto-install project dependencies if package.json exists
if [ -f "./package.json" ]; then
echo "π¦ Installing project dependencies..."
# Use the best available package manager
if [ -f "./pnpm-lock.yaml" ]; then
pnpm install
elif [ -f "./yarn.lock" ]; then
yarn install
else
npm install
fi
fi#!/bin/bash
# Update system PATH and configurations
# Update shell configuration
echo "export NODE_VERSION=$FNM_VERSION" >> ~/.bashrc
# Update system service configurations
sudo systemctl reload nginx 2>/dev/null || true- Check executable permissions:
ls -la ~/.fnm/hooks/ - Verify shebang line: Ensure scripts start with proper shebang (e.g.,
#!/bin/bash) - Test manually: Run the hook script directly to check for errors
- Check fnm logs: Look for hook-related error messages
- Check return codes: Ensure hooks exit with code 0 on success
- Handle missing dependencies: Check that required tools are installed
- Use absolute paths: Avoid relying on PATH environment in hooks
- Add error handling: Use
set -ein bash scripts for better error handling
# Add debugging to your hooks
#!/bin/bash
set -x # Enable debug output
set -e # Exit on error
echo "Hook started with PID: $$"
echo "Environment variables:"
env | grep FNM_
echo "Working directory: $(pwd)"
# Your hook logic here...
echo "Hook completed successfully"The hooks system is designed to be extensible. Future versions may include:
- Additional hook types (pre-use, post-use, pre-uninstall, post-uninstall)
- Hook configuration files
- Hook templates and generators
- Async hook execution
- Hook dependency management