是否可以在nodejs中倒回文件描述符游标?

Is it possible to rewind a file descriptor cursor in nodejs?

本文关键字:描述 文件 游标 回文 nodejs 是否      更新时间:2023-09-26

这是我在一个完美的世界里会做的:

fs.open('somepath', 'r+', function(err, fd) {
    fs.write(fd, 'somedata', function(err, written, string) {
       fs.rewind(fd, 0) //this doesn't exist
    })
})

这是我当前的实现:

return async.waterfall([
    function(next) {
      //opening a file descriptor to write some data
      return fs.open('somepath', 'w+', next)
    }, 
    function(fd, next) {
      //writing the data
      return fs.write(fd, 'somedata', function(err, written, string) {
        return next(null, fd)
      })
    },
    function(fd, next) {
      //closing the file descriptor
      return fs.close(fd, next)
    },
    function(next) {
      //open again to reset cursor position
      return fs.open('somepath', 'r', next)
    }
], function(err, fd) { 
   //fd cursor is now at beginning of the file 
})

我试图重置位置而不关闭fd使用:

fs.read(fd, new Buffer(0), 0, 0, 0, fn)

但是这会抛出Error: Offset is out of bounds

有没有一种方法来重置光标而不做这个可怕的hack?

/e: offset is out of bounds错误来自于这个异常。很容易通过将缓冲区大小设置为1来修复,但它不会倒回光标。可能是因为我们要求函数什么都不读取

今天,答案是它不在核心中,并且它不能用纯javascript添加。

有一个扩展node-fs-ext,它增加了一个seek函数来移动fd光标。这是在c++中完成的

相关的Stackoverflow问题

NodeJS v6.5.0有createReadStream方法,它接受一个选项数组。这些选项中包括startend属性。这些属性分别决定哪个字节应该被读取。

因此,如果您将start设置为0,它将从第一个字节读取文件。在这种情况下,如果将end设置为空,将导致流一直读取文件,直到文件的末尾。

例如:

fs.createReadStream('myfile.txt', {start: 0})

使用此读流将允许您读取整个文件

  1. fs.open获取fd
  2. fs.write(fd, string, position)
  3. fs.close(fd)