简体   繁体   中英

How to get current offset of stream or file descriptor?

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

There is no equivalent to ftell() or fseek() in node.js and I'm not really sure why. Instead, you generally specify the position you want to read or write at whenever you read or write with fs.read() or fs.write() . If you want to just write a bunch of data sequentially or you want buffered writing, then you would more typically use a stream which buffers and sequences for you.

Instead, if you want to know where data will be appended, you can fetch the current file length and then use that current file length to know if you're at the beginning of the file after opening it for appending.

Here's node.js code that does something similar to your C code.

const fs = require('fs');

async function myFunc() {
     let handle = await fs.promises.open("test.txt");
     try {
         const {size} = await handle.stat();
         await handle.appendFile(size ? "Subsequent line\n" : "First line\n");
     } finally {
         await handle.close();
     }
}

And, if you call this three times like this:

async function test() {
    await myFunc();
    await myFunc();
    await myFunc();
}

test();

You will get your desired three lines in the file:

First line
Subsequent line
Subsequent line

The fs.read has position parameter.

fs.read(fd, buffer, offset, length, position, callback)

The position parameter is important here.

Will this suffice your need unless I am not able to understand your question correctly?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM