Reading fs.read and fs.write, it seems that in Node.js no interface to the C function lseek is directly exposed; the current file descriptor position can be changed right before any fs.read
or fs.write
by the argument position
.
I strongly suspect that, at low level, the argument position
is handled with an lseek
call before the read or write operation, but what about the return value of lseek
?
To be more specific, to get the current file descriptor position in C, I can write:
int position = lseek(fd, 0, SEEK_CUR);
Is there a way in Node.js to get the same information?
It seems there's no "native" way for this. Probably because of
It is unsafe to use fs.write***() multiple times on the same file without waiting for the callback.
It would be even more so with something like getCurrentPosition
for a buffered IO. What it should return after write***
or read***
but before the callback is called?
But you can try and keep track of the current position yourself with the help of bytesRead
and bytesWritten
. And in case of streams there is chunk.length
, but don't forget about encodings in case of strings.
As a side note... you've wrote:
thinking to new features I thought this could be an useful info
If no one requested it, and you yourself is not sure what it can be used for, then I think it's a good idea to exercise YAGNI principle.
I strongly suspect that, at low level, the argument position is handled with an lseek call before the read or write operation, but what about the return value of lseek?
It is not used under the hood as said by Ben Noordhuis (libuv maintainer) :
lseek() is unpredictable with concurrent readers or writers. The libuv way is to use positional reads and writes (the offset argument to uv_fs_read() and uv_fs_write().)
This issue on node.js GitHub talk about how they manage the position argument to read and write data into the file.
Is there a way in Node.js to get the same information?
The accepted answer explain well how to do that: you need to track the read and written bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With