Skip to content

Instantly share code, notes, and snippets.

@troyk
Created November 17, 2010 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troyk/703839 to your computer and use it in GitHub Desktop.
Save troyk/703839 to your computer and use it in GitHub Desktop.
postgres log outputter
var fs = require("fs"),
spawn = require('child_process').spawn;
var filename = process.ARGV[2];
if (!filename)
return console.log("Usage: node <pgrecon.js> <filename>");
var tail = spawn("tail", ["-f", filename]);
console.log("start tailing");
var state = {
line: [],
part: '',
quoted: false,
slice_from: 0,
capture: function(data,index) {
if (this.quoted) return(false);
// capture slice without surrounding quotes
if (data[this.slice_from]==34) this.slice_from++;
this.part += data.slice(this.slice_from,data[index-1] == 34 ? index-1 : index).toString();
this.line.push(this.part);
this.part = '';
this.slice_from = index+1;
return(true);
},
line_complete: function() {
tail.emit('line',this.line);
this.line = [];
this.part = '';
this.quoted = false;
}
}
tail.on("line", function (line) {
console.log(line);
});
tail.stdout.on("data", function (data) {
state.slice_from = 0;
for (var i=0,len=data.length;i<len;i++) {
switch(data[i]) {
case 10: //line feed
if (state.capture(data,i)) state.line_complete();
break;
case 44: //comma
state.capture(data,i);
break;
case 34: //quote
state.quoted = !state.quoted;
break;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment