soyuka soyuka - 11 months ago 66
Node.js Question

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

This is what I would do in a perfect world:'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'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'somepath', 'r', next)
], function(err, fd) {
//fd cursor is now at beginning of the file

I tried to reset the position without closing the
by using:, new Buffer(0), 0, 0, 0, fn)

but this throws
Error: Offset is out of bounds

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

/e: The offset is out of bounds error comes from this exception. Easily fixed by setting a buffer size to 1 but it does not rewind the cursor. Maybe because we ask the function to read nothing.

Answer Source

Today, the answer is that it's not in the core, and that it can't be added with pure javascript.

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

Related Stackoverflow question.