Skip to content

Instantly share code, notes, and snippets.

@shinout
Created February 6, 2012 07:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shinout/1750489 to your computer and use it in GitHub Desktop.
Save shinout/1750489 to your computer and use it in GitHub Desktop.
fs.watchFile() -> fs.read()
var fs = require('fs');
var filename = process.argv[2];
fs.open(filename, 'r', function(err, fd) {
fs.watchFile(filename, function(cstat, pstat) {
var delta = cstat.size - pstat.size;
if (delta <= 0) return;
fs.read(fd, new Buffer(delta), 0, delta, pstat.size, function(err, bytes, buffer) {
console.log("err", err, "delta", delta, "bytes", bytes, "buffer", buffer.toString());
});
});
});
@laverdet
Copy link

laverdet commented Feb 6, 2012

If you want this to load data already in the file you will need to modify it:

var fs = require('fs');
var filename = process.argv[2];
fs.open(filename, 'r', function(err, fd) {
  if (err) throw new Error('Could not open file');
  var position = 0;
  fs.stat(filename, read);
  fs.watchFile(filename, read.bind(null, null));

  function read(err, stat) {
    var delta = stat.size - position;
    if (delta <= 0) return;

    fs.read(fd, new Buffer(delta), 0, delta, position, function(err, bytes, buffer) {
      console.log("err", err, "delta", delta, "bytes", bytes, "buffer", buffer.toString());
    });
    position = stat.size;
  } 
});

This is pretty rough code though, please be sure to handle errors. The file may be removed, truncated, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment