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

This is what I would do in a perfect world:

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

This is my current implementation:

 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 }) 

I tried resetting the position without closing fd with:

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

but this causes Error: Offset is out of bounds .

Is there a way to reset the cursor without doing this terrible hack?

/ e: an offset error outside comes from this exception . It is easily fixed by setting the buffer size to 1, but it does not rewind the cursor. Perhaps because we ask the function not to read anything.

+6
source share
3 answers

Today the answer is that it is not in the kernel and that it cannot be added with pure javascript.

There is a node-fs-ext extension that adds a seek function to move the fd cursor. This is done in C ++ here .

A related question about stop flow .

+1
source

NodeJS v6.5.0 has a createReadStream method that takes an array of parameters. Among these options are the start and end properties. These properties determine from and to which line should be read accordingly.

So, if you set start to 0 , it will read the file from the first line. Leaving end empty in this case will cause the stream to read the file completely to the end.

As an example:

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

Using this read stream will allow you to read the entire file.

+1
source

fs.write may be useful here:

  1. fs.open
  2. fs.write(fd, buffer, offset, length)
  3. fs.close(fd)
0
source

All Articles