Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimum Websocket Nodejs Tail Example

I'm trying to create a stream of data to the browser using websocket. The data is the output of a log file. (tail -f filename) Using node js, I've manage to log into stdout, but I haven't been able to create the server and create the client (js/html) code to create a websocket and receive all the output of this child process. Can anyone help me?

NODE.JS SERVER OUTPUTTING TAIL TO STDOUT (as seen in http://snippets.dzone.com/posts/show/12067)

var sys = require('sys')
var spawn = require('child_process').spawn;
var filename = process.ARGV[2];

if (!filename)
  return sys.puts("Usage: node <server.js> <filename>");

var tail = spawn("tail", ["-f", filename]);
sys.puts("start tailing");

tail.stdout.on("data", function (data) {
  sys.puts(data);
});

My goal is to have the simplest stream possible. Any other simple solution is well received for this. Thanks.

like image 906
jdelard Avatar asked Aug 17 '10 03:08

jdelard


2 Answers

This simple?

var sys = require('sys')
var spawn = require('child_process').spawn;
var filename = process.ARGV[2];
if (!filename)
  return sys.puts("Usage: node <server.js> <filename>");

var tail = spawn("tail", ["-f", filename]);

http = require('http');
http.createServer(function (req, res) {
  sys.puts("new connection..");
  res.writeHead(200, {'Content-Type': "text/plain;charset=UTF-8"});
  tail.stdout.on("data", function (data) {
    res.write(data);
  }); 
}).listen(3000);

Connect to the server and you'll get your tail. You'll have to watch for timeouts on the client side, depending on your browser, if the tail goes idle.

If you want to access this data from javascript within the browser, consider using socket.io as this will use the best method the browser has available to access the stream (websocket, long poll, flash etc.). If you need a client javascript example, I can post that too.

like image 186
bxjx Avatar answered Nov 16 '22 01:11

bxjx


This seems like an old question & very possibly the problem is already solved, but in case it isn't here is a gist https://gist.github.com/867575 .

it uses socket.io and instead of spawning "tail -f" processes(which takes more memory), fs.watchFile is used.

like image 33
NetRoY Avatar answered Nov 16 '22 01:11

NetRoY