Continiously tail a local file for new lines using Javascript in a browser

浪尽此生 提交于 2019-12-11 03:54:33

问题


I have a file that gets new lines appended to it frequently. I want to create a web application running in the browser using javascript that will be able to detect changes on that local file and print the new content that is added on the file.

My solution includes using javascript polling with setInterval and the new HTML5 File API. I load the file using an input file field and then poll the size of the file. Each time the size changes (in my case increases) this indicates to me that new content has been added to the file. I then slice the file using a Blob and only take the content that was appended using the old file size as start and the new file size as end.

Generally it works good with an average interval (I'm using 500ms) but I'm curious if there's a better solution cause this one sounds a bit like a hack to me.


回答1:


You can use js-logtail for following files like tail -f :

<head>
    <title>habitat parser log viewer</title>
    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript" src="logtail.js"></script>
    <link href="logtail.css" rel="stylesheet" type="text/css">
</head>

<body>
    <div id="header">
        js-logtail.
        <a href="./">Reversed</a> or
        <a href="./?noreverse">chronological</a> view.
        <a id="pause" href='#'>Pause</a>.
    </div>
    <pre id="data">Loading...</pre>
</body>

You don't even need a server side part, the webserver (as apache, lighthttpd) handles this with the HTTP Range header internally.



来源:https://stackoverflow.com/questions/28044799/continiously-tail-a-local-file-for-new-lines-using-javascript-in-a-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!