Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know file position in Node.js? - return value of lseek

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?

like image 814
Daniele Ricci Avatar asked Nov 22 '19 07:11

Daniele Ricci


2 Answers

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.

like image 73
x00 Avatar answered Sep 24 '22 06:09

x00


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.

like image 45
Manuel Spigolon Avatar answered Sep 22 '22 06:09

Manuel Spigolon