是否有可能回滚nodejs中的文件描述符游标?
这是我在一个完美的世界中所要做的:
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 })
我试图通过使用以下方法重置位置而不closuresfd
:
fs.read(fd, new Buffer(0), 0, 0, 0, fn)
但是这会抛出Error: Offset is out of bounds
。
有没有办法重置光标,而不做这个可怕的黑客 ?
/ e:偏移超出界限错误来自这个exception 。 通过将缓冲区大小设置为1可轻松修复,但不会倒回光标。 也许是因为我们要求函数什么也不读。
今天,答案是它不在核心,它不能用纯JavaScript添加。
有一个扩展节点fs-ext增加了一个seek
function来移动fd游标。 这在C ++中完成。
相关的Stackoverflow问题 。
NodeJS v6.5.0具有接受一系列选项的createReadStream方法。 这些选项包括start
和end
属性。 这些属性分别决定从哪一行读取。
所以,如果你将start
设置为0
,它将从第一行读取文件。 如果在这种情况下保持空白,将会使stream读取文件一直到结尾。
举个例子:
fs.createReadStream('myfile.txt', {start: 0})
使用这个读取stream将允许您读取整个文件。