Created
August 26, 2015 21:40
-
-
Save soldair/f250fb497ce592c3694a to your computer and use it in GitHub Desktop.
read the end of a file
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
var fs = require('fs') | |
// usage example: | |
// var t = require('./this-file.js') | |
// t('/var/log/boot.log',1024,function(err,data){ console.log(data+'')}) | |
// | |
module.exports = function(file,lastNBytes,cb){ | |
var fd, size, called | |
var orig = cb | |
var start = function fn(err,data){ | |
if(steps.length && !err) { | |
return steps.shift(next) | |
} | |
if(called) return; | |
called = 1 | |
orig(err,data) | |
if(fd) fs.close(fd,function(){}) | |
} | |
var steps = [ | |
// first open the file | |
function(next){ | |
fs.open(file,'r',function(err,_fd){ | |
if(err) return cb(err) | |
fd = _fd | |
next() | |
}) | |
}, | |
// then stat the file to get the size | |
function(next){ | |
fs.stat(file,function(err,stat){ | |
if(err) return cb(err) | |
size = stat.size | |
next() | |
}) | |
}, | |
// read the file offset you want and close the file | |
function (next){ | |
fs.read(fd, new Buffer(lastNBytes), size-lastNBytes, lastNBytes, 0, function(err,bytesRead,data){ | |
if(err) return next(err) | |
next(false,data.slice(0,bytesRead)) | |
}) | |
} | |
] | |
start(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sorry, but this code does not work, because
next is undefined
forvar start
.