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

soy*_*uka 6 javascript node.js

这就是我在完美世界中所做的事情:

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

这是我目前的实施:

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 
})
Run Code Online (Sandbox Code Playgroud)

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

fs.read(fd, new Buffer(0), 0, 0, 0, fn)
Run Code Online (Sandbox Code Playgroud)

但这引发了Error: Offset is out of bounds.

有没有办法重置光标而不做这个可怕的黑客攻击

/ e:偏移超出范围错误来自此异常.通过将缓冲区大小设置为1轻松修复,但不会回退光标.也许是因为我们要求函数不读.

soy*_*uka 1

今天的答案是它不在核心中,而且无法用纯javascript添加。

有一个扩展node-fs-ext,添加了seek移动fd光标的功能。这是在此处用 C++ 完成的。

相关的Stackoverflow 问题