Home » Javascript » fs readfile position if already at end of file

fs readfile position if already at end of file

Posted by: admin August 19, 2018 Leave a comment

Questions:

I’m writing something that is effectively “tailing” a file – every now and then the browser polls back and says “I read up to position 23123, give me anything more”. I’ve written this function which is supposed to give me anything new:

async function readNew( filename, mark )
{
    var fileDescriptor = await fs.open( filename, "r" );
    var buffer = new Buffer( 32768 );
    var result = await fs.read( fileDescriptor, buffer, 0, buffer.length, mark );
    await fs.close( fileDescriptor );
    return result;
}

and it works perfectly if there is something new. If there’s not, for some reason it goes back to the beginning and reads the entire file! So for instance, if mark is 16427 – and the file is of size 16427 – I get 16427 bytes read – and what I want is 0.

Any ideas how I can fix this reliably, and with some level of performance?
Most of the time, there won’t be any changes – so I want that case to be as fast as possible.

Answers: