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!
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');
});