BASH
Automate Node.js Dependency Installation
Create a bash script to intelligently check for Node.js project dependencies (`node_modules`) and automatically install them if missing using npm or yarn.
#!/bin/bash
# This script checks if Node.js project dependencies are installed
# If not, it attempts to install them using yarn (if available) or npm.
PROJECT_ROOT=$(pwd)
NODE_MODULES_PATH="$PROJECT_ROOT/node_modules"
echo "Checking for Node.js dependencies in $PROJECT_ROOT..."
if [ ! -d "$NODE_MODULES_PATH" ]; then
echo "node_modules directory not found. Attempting to install dependencies..."
# Check if yarn is installed and use it
if command -v yarn &> /dev/null; then
echo "Yarn detected. Installing with yarn..."
yarn install
INSTALL_STATUS=$?
# Else, use npm
elif command -v npm &> /dev/null; then
echo "npm detected. Installing with npm..."
npm install
INSTALL_STATUS=$?
else
echo "Error: Neither yarn nor npm found. Please install Node.js and a package manager."
exit 1
fi
if [ $INSTALL_STATUS -eq 0 ]; then
echo "Dependencies installed successfully!"
else
echo "Error: Dependency installation failed."
exit 1
fi
else
echo "node_modules directory found. Dependencies appear to be installed."
echo "To force a re-installation, delete node_modules and run this script again."
fi
echo "Dependency check complete."
How it works: This script helps automate the setup of Node.js projects. It first verifies the existence of the `node_modules` directory in the current project. If it's missing, the script checks for the presence of `yarn` and uses it to install dependencies. If `yarn` is not available, it falls back to `npm`. This ensures that required packages are always present before running development or build tasks, streamlining developer workflow.