Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my node.js application occasionally hang when I don't have the terminal open?

Tags:

node.js

tmux

I have a nodejs application that I run like this, over SSH:

$ tmux
$ node server.js

This starts my node application in a tmux session.

Obviously, I don't have the SSH session open all the time.

What I've been finding is that occasionally my application can get in a state where it won't server up any pages. This might be related to the application itself, or perhaps just a poorly disconnected SSH session.

Either way, simply logging into SSH, running:

$ tmux attach

And giving focus to the pane makes everything responsive again.


I thought the entire point of node.js was that everything is non-blocking - then what's going on here?

like image 701
Eric Avatar asked Jan 13 '13 22:01

Eric


1 Answers

When a pane is is copy mode, tmux does not read from its tty. If some program running “in” in the tty continues to generate output, then the OS’s tty buffer will eventually fill and cause the writing process/thread to block. I do not know the internals of Node.js, but it may not expect writes to stdout/stderr to block: the console functions do not seem to have callbacks, so they may actually be blocking.

So, Node.js could very well end up blocked if the pane in which it was running was left in copy mode when your SSH connection was dropped.

If you need to assure non-blocking logging, then you might want to redirect (or tee) your stdout and stderr to a file and use something like less to view the prior logs (avoiding tmux’s copy mode since it might cause blocking).

Maybe something like this:

# Redirect stdout/stderr to a file, running Node.js in the background.
# Start a "less +F" on the log so that we immediately have a "tail" running.
node app.js >>app.log 2>&1 & less +F app.log

Or

# This pane will act as a 'tail -f', but do not use copy-mode here.
# Instead, run e.g. 'less app.log' in another pane to review prior logs.
node app.js 2>&1 | tee -a app.log

Or, if you are using a logging library, it might have something that you can use to automatically write to files.

like image 101
Chris Johnsen Avatar answered Sep 22 '22 09:09

Chris Johnsen