I would like to efficiently read the last X bytes of a very large file using node.js. What's the most efficient way of doing so?
As far as I know the only way of doing this is by creating a read stream and loop until a hit the byte index.
Example:
// lets assume I want the last 10 bytes;
// I would open a stream and loop until I reach the end of the file
// Once I did I would go to the last 10 bytes I kept in memory
let f = fs.createReadStream('file.xpto'); //which is a 1gb file
let data = [];
f.on('data', function(data){
for (d of data){
data.push(d)
data = data.slice(1,11); //keep only 10 elements
}
})
f.on('end', function(){
// check data
console.log('Last test bytes is', data)
})
f.resume();