-1

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.

1
  • I only know C++ can do this because it has seekp. But in Nods.js, you must read it to a Buffer and slice it. Commented Jun 23, 2024 at 11:45

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.