views:

349

answers:

1

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.

+2  A: 

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.

bxjx
+1 for socket.io
Frankie