In nodejs, how do I overwrite a section of a file without creating additional files or reading all the data into memory?
let filename= '123.txt';
const fd = fs.openSync(filename, 'w+');
fs.writeSync(fd, Buffer.from('123'), 0, 3, 5);
fs.closeSync(fd);
This code is expected to overwrite 3 bytes of the file starting from 6, but it completely erases the contents and inserts 5 null bytes at the beginning, if you set the a+
flag, it always writes to the end of the file.
Mainly you'd want to use r+ flag instead of w+. There are already answers present to similar questions , you can reference them or even refer to docs for further information.