Webtailf (tail -f to the web-bro

作者: 小武子 | 来源:发表于2017-01-12 23:13 被阅读298次

tail命令和tailf命令对于每个玩linux的人相比都特别熟悉,这里就不细表了。

但是如果你想把tailf后输出到web端,怎么做?对!长连接websocket(我称之为webtailf)。

websocketwebsocket

但是具体要怎么做?我搜了github,发现竟然没有好的解决方案,不过在这篇文章里面,发现了一条神奇的命令:

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

ps. 简书代码不支持折行,我给手动折行了,人家本身是一行的。

然后配合这段js代码:

new EventSource("http://localhost:1234/").onmessage = function(e) {
    console.log(e.data);
};

你就可以霸气的按F12,在console里面看到tail命令输出的内容了!


咱们看看这行霸气的shell命令(真是1行shell==1w行C)做了什么:

(echo -e 'HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: *\nContent-type: text/event-stream\n'

这个简单,就是返回http头,说明这个是长连接。

&& tail -f /path/to/some/file | sed -u -e 's/^/data: /;s/$/\n/') | nc -l 1234

这句是将文件tailf出来,然后传给sed,进行断句,然后在每行前面加上data: ,之后和http头一起打包,传给netcat,通过监听1234端口,发送出去,之后浏览器就可以拿到tailf的信息了。

当然,这只是一个玩具,因为nc只支持一次连接,如果连接断了,需要重启nc。

那么,说到最后,什么才是可用的?

websocketd --port 1234 tail -f /path/to/file

官网在这里,Github在这里,7K Star哦!


为了你们方便,同样给出客户端的demo吧(同样也是简单到爆!):

var ws = new WebSocket('ws://localhost:1234/');
ws.onmessage = function(event) {
     console.log(event.data);
};

相关文章

网友评论

    本文标题:Webtailf (tail -f to the web-bro

    本文链接:https://www.haomeiwen.com/subject/ciejbttx.html