3

Using Node.js, is there a way to overwrite all the file contents with fs.write instead of fs.writeSync? It appears that fs.write will write in the bytes in the position given but leave the other bytes intact?

https://nodejs.org/api/fs.html#fs_fs_write_fd_buffer_offset_length_position_callback

0

1 Answer 1

8

fs.write() writes bytes into the file positions you give it. It replaces those bytes in the file. It does not affect any other bytes in the file. That's how it works.

You can separately use fs.ftruncate() to change the length of an open file descriptor and, if you pass it 0 as the new length, it will truncate the file a zero length file which you could then fs.write() new bytes to.

If you use the O_TRUNC flag with fs.open(), then it will truncate any existing file to zero length when you open it and then you can fs.write() into the now empty file.

If you just wish to replace the entire contents of a file with one operation, you can use fs.writeFile() instead. That will open the file for writing, clearing any previous contents (can modify behavior with options you pass it), write data to the file and then close it.

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.