Created
May 18, 2011 12:29
-
-
Save foogoof/978488 to your computer and use it in GitHub Desktop.
Express / node / socket.io code to stream unix child process output over websockets
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
// | |
// Just skip to the bottom | |
// | |
var express = require('express'); | |
var io = require('socket.io'); | |
var app = module.exports = express.createServer(); | |
// Configuration | |
app.configure(function(){ | |
app.set('views', __dirname + '/views'); | |
app.set('view engine', 'html'); | |
app.use(express.bodyParser()); | |
app.use(express.methodOverride()); | |
app.use(app.router); | |
app.use(express.static(__dirname + '/public')); | |
app.register('.html', require('ejs')); | |
}); | |
app.configure('development', function(){ | |
app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); | |
}); | |
app.configure('production', function(){ | |
app.use(express.errorHandler()); | |
}); | |
// Routes | |
app.get('/', function(req, res){ | |
res.render('index', { | |
title: 'Express' | |
}); | |
}); | |
// Only listen on $ node app.js | |
if (!module.parent) { | |
app.listen(3000); | |
console.log("Express server listening on port %d", app.address().port); | |
} | |
var spawn = require('child_process').spawn; | |
var socket = io.listen(app, {transports:['websocket']}); | |
socket.on('connection', | |
function(client){ | |
client.on('message', | |
function(path) { | |
console.log("I gots a path: " + path); | |
tail_f(path, client); | |
}); | |
}); | |
var tail_f = function (file, client) { | |
var proc = spawn('tail', ['-f', file]); | |
proc.stdout.on('data', | |
function(data) { | |
console.log('file: (' + file + ') ' + data.toString()); | |
client.send(data.toString()); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment