~ read.

Debug a Node.js app from a Vagrant VM

This is just a quick reminder to myself, and can maybe be usefull to others.

Manually

Install node-inspector :

npm install -g node-inspector

Start your app in debug mode :

node --debug app.js

Open a second SSH session on your Vagrant box.

Start the debugger :

node-inspector

You can now access the debugger here : http://YOUR-VAGRANT-VM-IP:8080/debug?port=5858

If your Node app already use the 8080 port, you can start the debugger with a custom one :

node-inspector --web-port 8081

With a login script

You can create a login script that will be executed every time you connect to the Vagrant box with your user.

This script will use tmux to create multiple consoles (windows) on the same shell. This way you can have your app, grunt and node-inspector running on the same shell.

Here is the script I'm using on some projects (change the variables at the beggining).

Don't forget to install tmux too (apt-get install tmux) !

#!/bin/bash

# IMPORTANT! Do not forget to change these values!
appDir="/vagrant"  
appStartScript="app.js"  
nvmShPath="/home/vagrant/nvm/nvm.sh"  
nodeDebugPort="5858"  
nodeInspectPort="8080"

# Source NVM
source "$nvmShPath"

session="dev"  
window="devWindow"

attachSession=$(tmux attach-session -t "$session")

if (tmux has-session -t "$session" 2> /dev/null); then  
    echo "Session $session exists."
else  
    echo "No tmux session found, create one."

    # First pane, cd in app dir
    tmux new-session -d -s "$session" -n "$window" "bash"
    tmux send-keys -t "$session":"$window" "cd \"$appDir\"" Enter
    tmux send-keys -t "$session":"$window" "node --debug=$nodeDebugPort \"$appStartScript\"" Enter

    # Second pane, grunt
    tmux split-window -t "$window" -h "bash"
    tmux send-keys -t "$session":"$window" "cd \"$appDir\"" Enter
    tmux send-keys -t "$session":"$window" "grunt build" Enter
    tmux send-keys -t "$session":"$window" "grunt watch" Enter

    # Third pane, the app
    tmux split-window -t "$window" "bash"
    tmux send-keys -t "$session":"$window" "cd \"$appDir\"" Enter
    tmux send-keys -t "$session":"$window" "node-inspector --debug-port $nodeDebugPort --web-port $nodeInspectPort" Enter

    # Select first pane
    tmux select-pane -t "$session" -L

    # Fourth pane ?
    #tmux select-pane -t "$session" -L
    #tmux split-window -t "$window" "bash"
    #tmux send-keys -t "$session":"$window" "echo fourth" Enter

    tmux attach-session -t "$session"
fi

tmux attach-session -t "$session"