Skip to content

Instantly share code, notes, and snippets.

@soldair
Created August 26, 2015 21:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save soldair/f250fb497ce592c3694a to your computer and use it in GitHub Desktop.
Save soldair/f250fb497ce592c3694a to your computer and use it in GitHub Desktop.
read the end of a file
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();
}
@makamekm
Copy link

makamekm commented Apr 17, 2020

Sorry, but this code does not work, because next is undefined for var start.

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