In Node.js, is there any way of getting the current offset of a file descriptor or stream? Presently, it is possible to set the offset of a file descriptor, but there seems to be no way to get it.
In C, getting the offset of a file stream is done via ftell
, and a file descriptor via lseek(fd, 0, SEEK_CUR)
.
Example
If a Node.js program needs to check whether there is prior data in a file after opening it in append mode, a call to ftell
would help in this case. This can be done in C as follows:
#include <stdio.h>
int main() {
FILE* f = fopen("test.txt", "a");
fprintf(f, ftell(f) ? "Subsequent line\n" : "First line\n");
fclose(f);
}
Running the above program three times, test.txt
becomes:
First line
Subsequent line
Subsequent line
Prior Art
- GitHub issue filed for old version of node. The discussion mentions
bytesWritten
andbytesEmitted
, neither of which is equivalent toftell
(in the above C example, the bytes written when the file is first opened is always 0). https://github.com/nodejs/node-v0.x-archive/issues/1527. - The
fs-ext
NPM package. Exposes the low-levellseek
for use in Node.js. https://www.npmjs.com/package/fs-ext.