这就是我在完美世界中所做的事情:
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:偏移超出界限错误来自this exception。通过将缓冲区大小设置为1轻松修复,但不会回退光标。也许是因为我们要求函数不读。
答案 0 :(得分:1)
今天,答案是它不在核心,并且不能用纯javascript添加。
有一个扩展node-fs-ext,可以添加seek
函数来移动fd游标。这是在C ++ here中完成的。
答案 1 :(得分:1)
NodeJS v6.5.0具有createReadStream方法,该方法接受一组选项。其中包括start
和end
属性。这些属性分别确定从和到哪一行应该被读取。
因此,如果您将start
设置为0
,它将从第一行读取文件。在这种情况下将end
留空会导致流一直读到文件。
举个例子:
fs.createReadStream('myfile.txt', {start: 0})
使用此读取流将允许您读取整个文件。
答案 2 :(得分:0)
fs.write在这里可能会有所帮助:
fs.open
获得fd fs.write(fd, string, position)
fs.close(fd)