3

I am using node.js for the first time. I want to write a file using the fs.write function. I have taken reference from its file system docs. Its syntax is like this: fs.write(fd, buffer, offset, length, position, callback)

I know how to use fd, buffer and callback in this, but I am not able to figure out how to pass offset, length and position.

Should they be some integers or string?... or what? I am not able to find out.

karel
  • 5,489
  • 46
  • 45
  • 50
Nikita
  • 33
  • 1
  • 4

1 Answers1

1

offset and length are integers referring to positions of the Buffer. offset is where in the Buffer should we write from; length is how many bytes should be written.

So, as an example, if you had a Buffer with data abcdefghijklmnopqrstuvwxyz, you could write cdef with offset: 2, length: 4.

position is an integer for where in the file the data should be written. So, if you have an existing file, you could overwrite part of it by setting the position to something between the beginning and the end.

Scimonster
  • 32,893
  • 9
  • 77
  • 89
  • var wbuffer=new Buffer('message'); var bufferPosition=0, bufferLength=wbuffer.length, filePosition=null; fs.write('public/file1.txt',wbuffer,bufferPosition,bufferLength,filePosition,function(err,written) { console.log(err); res.end(); }); I am using it as above but still not able to write file. An error is coming saying bad argument. – Nikita Nov 10 '14 at 09:38
  • 1
    The first argument should be a file descriptor, that is, the result of `fs.open(filename, "w", callback)`. `fs.write` does support passing a string as the first argument. – RickN Nov 10 '14 at 10:01