Last active
August 29, 2015 14:08
-
-
Save jberger/93b3a192fc68a0d7ca14 to your computer and use it in GitHub Desktop.
Stream command output to browser via websocket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use Mojolicious::Lite; | |
use 5.20.0; | |
use experimental 'signatures'; | |
get '/' => {template => 'index'}; | |
my $cmd = 'sleep 1; echo "hello world"; sleep 1; echo "yo peeps"'; | |
websocket '/output' => sub ($c) { | |
$c->send("Running command: $cmd\n"); | |
open my $output, '-|', $cmd or die "Couldn't spawn: $!"; | |
my $stream = Mojo::IOLoop::Stream->new($output); | |
$stream->on(read => sub ($stream, $bytes) { $c->send({text => $bytes}) }); | |
my $sid = Mojo::IOLoop->stream($stream); | |
$c->on(finish => sub { Mojo::IOLoop->remove($sid) }); | |
}; | |
app->start; | |
__DATA__ | |
@@ index.html.ep | |
<pre id="log"></pre> | |
<script> | |
var ws = new WebSocket('<%= url_for('output')->to_abs %>'); | |
var log = document.getElementById('log'); | |
ws.onmessage = function (event) { log.innerHTML += event.data }; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm using this mechanism in https://github.com/jberger/Mojolicious-Plugin-TailLog