5

I want to write to a file multiple times using the Writable Stream in nodejs. The problem is that I also want to specify the postion also to this writer.

Here is some background - I want to create a multi threaded downloader. The data which comes as a response needs to be saved to the disk. The order of the data chunks can be random and that is why I need to pass the position parameter also to the writeable stream.

I am using writable stream instead of fs.write because the documentation says so -

Note that it is unsafe to use fs.write multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream is strongly recommended.

Thanks!

tusharmath
  • 10,622
  • 12
  • 56
  • 83

1 Answers1

3

You can do this using the start option, however, it requires the file exist and have a size >= offset + chunkToWrite.length. This would put you back to using fs.writeFile with some dummy contents whose size is >= the size of the file to be downloaded, and needing to wait for the callback from that initial write. For example:

var buffer = new Buffer (fileSize);
buffer.fill('0');

fs.writeFile('./file', buffer, function() {
  var writeStream = fs.createWriteStream('./file',{flags: 'r+', mode: 0777, start: 10});
  writeStream.write('HELLO AFTER 10');
});
Jonathan Wiepert
  • 1,222
  • 12
  • 12
  • 1
    for node v6, the buffer must be of size smaller than 2GB (2^31 - 1). it is given in [`official docs`](https://nodejs.org/api/buffer.html#buffer_class_method_buffer_alloc_size_fill_encoding) – zhirzh Jun 28 '16 at 22:21