How to stream/pipe a file to the browser from CLI (using eventsource or websockets)

It may be useful to stream/pipe a file content (a “tail -f”) to the browser, maybe a log.

Using Server-sent events and netcat@wiki

# on the server, install netcat
$ sudo apt-get install netcat | sudo apt-get install netcat-openbsd

# and stream a file
$ (echo -e "HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: *\nContent-type: text/event-stream\n" && tail -f file | sed -u -e 's/^/data: /;s/$/\n/') | nc -l 1234

# on the browser, run js snippet
new EventSource("http://localhost:1234/").onmessage = function(e) { console.log(e.data); };

See sse@caniuse and sse@html5rocks

Using WebSocket and websocketd (static binary written in go)

# on the server, install websocketd, see https://github.com/joewalnes/websocketd/wiki/Download-and-install

# and stream a file
$ websocketd --port 1234 tail -f /path/to/file

# on the browser, run js snippet
new WebSocket("ws://localhost:1234/").onmessage = function(e) { console.log(e.data); };
# or from the cli, using http://einaros.github.io/ws/
$ npm install -g ws ; wscat -c ws://localhost -p 1234

See ws@caniuse and ws@html5rocks

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s