monitor-node-processes.sh
1 #!/usr/bin/env bash 2 3 # Display currently running npm and node scripts 4 # Shows: PID, Runtime, CPU%, Script Name, Full Path 5 6 set -euo pipefail 7 8 echo "=== Node.js & NPM Process Monitor ===" 9 echo "" 10 11 # Find actual node/npm processes (filter by command name, not just path) 12 # This excludes system processes that just have "node" in their path 13 processes=$(ps aux | awk '$11 ~ /^(node|npm)$/ || $11 ~ /\/node$/ || $11 ~ /\/npm$/ || $0 ~ /node .*\.js/') 14 15 if [[ -z "$processes" ]]; then 16 echo "No Node.js or npm processes currently running." 17 exit 0 18 fi 19 20 # Print header 21 printf "%-8s %-12s %-8s %-30s %s\n" "PID" "RUNTIME" "CPU%" "SCRIPT" "PARAMETERS" 22 printf "%-8s %-12s %-8s %-30s %s\n" "---" "-------" "----" "------" "----------" 23 24 # Parse and display each process 25 echo "$processes" | while IFS= read -r line; do 26 # Extract fields from ps aux output 27 pid=$(echo "$line" | awk '{print $2}') 28 cpu=$(echo "$line" | awk '{print $3}') 29 30 # Get detailed info using ps with custom format 31 runtime=$(ps -p "$pid" -o etime= 2>/dev/null | xargs || echo "N/A") 32 full_cmd=$(ps -p "$pid" -o args= 2>/dev/null || echo "N/A") 33 34 # Skip processes that no longer exist (race condition) 35 if [[ "$runtime" == "N/A" ]] || [[ "$full_cmd" == "N/A" ]]; then 36 continue 37 fi 38 39 # Extract script name and parameters 40 if echo "$full_cmd" | grep -q "npm run"; then 41 script_name=$(echo "$full_cmd" | grep -oP 'npm run \K\S+' || echo "npm") 42 # Parameters after npm run command 43 params=$(echo "$full_cmd" | sed -E 's/.*npm run [^ ]+ ?//' || echo "") 44 elif echo "$full_cmd" | grep -q "npm"; then 45 script_name="npm" 46 params=$(echo "$full_cmd" | sed 's/npm *//' || echo "") 47 elif echo "$full_cmd" | grep -qE "node.*\.js"; then 48 script_name=$(echo "$full_cmd" | grep -oP '[^ ]+\.js' | head -1 | xargs basename || echo "node") 49 # Get everything after the .js file 50 params=$(echo "$full_cmd" | sed -E 's|.*\.js *||' || echo "") 51 else 52 script_name=$(echo "$full_cmd" | awk '{print $1}' | xargs basename) 53 params=$(echo "$full_cmd" | cut -d' ' -f2- || echo "") 54 fi 55 56 # Truncate script name if too long 57 script_name_short=$(echo "$script_name" | cut -c1-30) 58 59 # Print formatted output 60 printf "%-8s %-12s %-8s %-30s %s\n" "$pid" "$runtime" "${cpu}%" "$script_name_short" "$params" 61 done 62 63 echo "" 64 echo "Run 'kill <PID>' to stop a process"