在Node.js中,有没有办法获取文件描述符或流的当前偏移量?目前可以set the offset of a file descriptor,但似乎没有办法。
在C语言中,通过ftell
获取文件流的偏移,并通过ftell
获得文件描述符。
如果Node.js的程序需要检查是否存在以附加模式打开它之后是在一个文件中的数据之前,向通话lseek(fd, 0, SEEK_CUR)
将有助于在这种情况下。可以在C中完成以下操作:
lseek(fd, 0, SEEK_CUR)
运行上述程序三次,ftell
变为:
#include <stdio.h>
int main() {
FILE* f = fopen("test.txt", "a");
fprintf(f, ftell(f) ? "Subsequent line\n" : "First line\n");
fclose(f);
}
test.txt
和First line
Subsequent line
Subsequent line
,两者均不等于bytesWritten
(在上述C示例中,首次打开文件时写入的字节始终为0)。 bytesEmitted
。ftell
NPM程序包。公开低级https://github.com/nodejs/node-v0.x-archive/issues/1527供Node.js使用。 fs-ext
。lseek
位置参数在这里很重要。
除非我无法正确理解您的问题,这足以满足您的需要吗?
这里的node.js代码与您的C代码相似。
fs.read()
而且,如果您这样打三遍:
fs.write()
您将在文件中获得所需的三行:
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();
}
}